Cpp - constexpr constant expression

Introduction

A constant expression function is a function whose value can be determined by the compiler.

And compiler can use that constant value to substitute the function call.

The function must be preceded by the keyword constexpr and meet three criteria:

  • function must return a value (not void)
  • entire body of the function must be a single return statement that returns an expression
  • expression must evaluate to a constant after substitution.

The constant expression cannot be called before it is defined.

The following code has a valid constant expression:

constexpr double expand(int original) 
{ 
    return original * 1.5; 
} 

The following code shows how to use constexpr to create a function to return array length.

The array size set between the [ and ] brackets must be a constant.

Demo

#include <iostream> 
 
constexpr int getArraySize() 
{ 
 return 1024; //w w  w .  j av  a  2s.  c  o  m
} 
 
int main() 
{ 

    int bolts[getArraySize()]; 
    int boltsSize = sizeof(bolts) / sizeof(bolts[0]); 
     
    for (int i = 0; i < boltsSize; i++) 
    { 
               bolts[i] = i * boltsSize; 
    } 
     
    std::cout << "Value of bolts[10]: " << bolts[10] << std::endl; 
  
    return 0; 
}

Result