Initializing a constexpr with a const, — int vs float

前端 未结 2 1880
情歌与酒
情歌与酒 2021-01-17 08:05

I\'m wondering why the integer ii is initiallized at compile time, but not the float ff here:

int main() {
  const int i = 1;
  con         


        
相关标签:
2条回答
  • 2021-01-17 08:19

    Constant variables of integral types with constant initializers are integral constant expressions (de facto implicitely constexpr; see expr.const in ISO C++). float is not an integral type and does not meet the requirements for constant expression without the use of constexpr. (A similar case is why int can be but float cannot be a template parameter.)

    0 讨论(0)
  • 2021-01-17 08:26

    In C++ constant integers are treated differently than other constant types. If they are initialized with a compile-time constant expression they can be used in a compile time expression. This was done so that array size could be a const int instead of #defined (like you were forced in C):

    (Assume no VLA extensions)

    const int s = 10;
    int a[s];          // OK in C++
    
    0 讨论(0)
提交回复
热议问题