C++ constexpr Constants at compile-time

Introduction

Another const qualifier is the constant expression named constexpr.

It is a constant that can be evaluated at compile-time.

Initializers for constant expressions can be evaluated at compile-time and must themselves be constant expressions.

Example:

int main() /*from  w ww  . ja v  a2 s.  c  o  m*/
{ 
    constexpr int n = 123;           //OK, 123 is a compile-time constant   
                                             // expression 
    constexpr double d = 456.78;     //OK, 456.78 is a compile-time constant   
                                             // expression 
    constexpr double d2 = d;         //OK, d is a constant expression 
    int x = 123; 
    constexpr int n2 = x;           //compile-time error 
                                     // the value of x is not known during   
                                             // compile-time 
} 



PreviousNext

Related