I've encountered a weird issue when trying to declare array on the stack in C. I always thought (until now at least) that it was impossible to declare array on the stack without a constant expression. E.g trying to compile the following code on VS2015 on Windows:
int main()
{
int i = 3;
int test[i];
return 0;
}
Yields an "Expression must have a constant value" error, which is what I expected, but compiling the same code with gcc and clang on a Linux machine works. At first I thought it's probably the compilers inferring stuffs, so I tried the following:
int main()
{
int i = 3;
int j = i*i;
int test[j];
return 0;
}
And again VS2015 complained with the same error but gcc and clang compiled it just fine! I immediately thought, OK so maybe those compilers are inferring that as well, it is after all, just "constant" expressions. So I tried the following:
int main()
{
int i = getchar();
int test[i];
return 0;
}
Surely the compiler can't infer this, the value of i
when used to declare test
can only be known at runtime, but to my surprise, again, VS2015 complained, but gcc and clang compiled it...
Even adding the following:
int main()
{
int i = getchar();
int test[i];
printf("%d\n", sizeof(test) / sizeof(int));
return 0;
}
And entering the character x
which it's value is 120 in the ASCII table, outputting 120.
What's going on?