4

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?

Abhishek Chandel
  • 1,294
  • 2
  • 13
  • 19
  • 1
    Try `constexpr std::size_t three() { // ...` – πάντα ῥεῖ Jul 17 '14 at 03:27
  • I Know i can use it, But my question is why program 2 is successfully compiled but not program 1. – Abhishek Chandel Jul 17 '14 at 03:28
  • 5
    Neither is valid C++. Whatever language extension you're using probably has a rule preventing the first. – chris Jul 17 '14 at 03:29
  • I just tested both and both didnt compile on VS2010... – Samer Jul 17 '14 at 03:35
  • @Samer That's because no version of VS supports very many C99 features other than the ones that are also part of C++. The OP would get warnings from gcc too if he enables `-Wall` and/or `-pedantic` on gcc/clang – Praetorian Jul 17 '14 at 03:37
  • @Samer [visual studio never supported VLA even in C since until recently, it did not support any C99](http://stackoverflow.com/a/21880957/1708801). – Shafik Yaghmour Jul 17 '14 at 03:38
  • @Praetorian Actually, `-Wall` [doesn't warn for this](http://coliru.stacked-crooked.com/a/d36ec6628aff1074). You need `-pedantic`. – T.C. Jul 17 '14 at 03:39
  • Also related to [this](http://stackoverflow.com/questions/21273829/does-int-size-10-yield-a-constant-expression). – Shafik Yaghmour Jul 17 '14 at 03:45

1 Answers1

4

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.

Community
  • 1
  • 1
T.C.
  • 133,968
  • 17
  • 288
  • 421