DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

constexpr c++11

constexpr is new keyword in c++11 and it is used with data type(either build in or user defined) and function. It defines that this value is constant and evaluated during compilation. In other word, it has two functionalities:

  1. Make the variable or object const (Must be initialised otherwise get compilation error)
  2. Evaluate the function at compile time.

Source code with example:

//Header File
#include<iostream>
#include<array>

//constexpr function

constexpr int sq(int x) { return(x*x);}

int main()
{
    std::cout<<"In constexpr"<<std::endl;

    //constexpr int sz; //constexpr must be instailized
    //other wise we will get error: uninitialized const ‘sz’
    constexpr int sz = 5;         //const functionality

    //std::array
    std::array<int, sz> arr1;

    //calling function with constexpr
    std::array<int, sq(5)> arr2;   //evaluation at compile time
    std::cout<<"size:"<<sizeof(arr2)<<std::endl;
    //get 100 = 25*4(int size)

    return 0;
}

Output:

In constexpr
size:100

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer