The constexpr Keyword - C++ Data Type

C++ examples for Data Type:constexpr

Introduction

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

The function must return a value (not void)

The entire body of the function must be a single return statement that returns an expression

The expression must evaluate to a constant after substitution.

Here's a snippet of code that is a valid constant expression:

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

const int getArraySize(int hours) 
{ 
    return 60 * 60 * hours; 
} 

int ticks[getArraySize(24)]; 

Example,

Demo Code

#include <iostream> 
 
constexpr int getArraySize() 
{ 
 return 1024; // ww  w  .  j  a  va  2  s .  c  om
} 
 
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


Related Tutorials