JavaEar 专注于收集分享传播有价值的技术资料

array bound is not an integer constant before is resolved by declaring array inside main

program 1

#include <iostream>

std::size_t three() {
    return 3;
}

int i[three()];

int main() 
{
    return 0;
}

program 2

std::size_t three() {
    return 3;
}

int main() 
{
    int i[three()];
    return 0;
}

The issue here is Program 1 as expected gives the compilation error

"error: array bound is not an integer constant before ']' token"

But I have no idea why the Program 2 is compiled successfully?

1个回答

    最佳答案
  1. C99 allows int i[three()]; to declare a variable-length array, but only if it is not of static or thread storage duration. Declaring it in file scope means that it has static storage duration, so it's illegal even in C99. Declaring it in main() the way you did means that it has automatic storage duration, which is allowed in C99.

    Some compilers such as GCC and Clang supports it in C89 and C++ modes as well, as an extension. But this is not legal C++ as far as the standard is concerned. Both GCC and Clang will produce a warning for this code if you compile with -pedantic.