gcc complains about this:
#include <stdio.h>
static const int YY = 1024;
extern int main(int argc, char*argv[])
{
static char x[YY];
}
$ gcc -c test1.c
test1.c: In function main':
test1.c:5: error: storage size of
x' isn't constant
test1.c:5: error: size of variable `x' is too large
Remove the “static” from the definition of x and all is well.
I'm not exactly clear what's going on here: surely YY is constant?
I had always assumed that the "static const" approach was preferable to "#define". Is there any way of using "static const" in this situation?
In C, a const variable isn't a "real" compile-time constant... it's really just a normal variable that you're not allowed to modify. Because of this, you can't use a const int
variable to specify the size of an array.
Now, gcc has an extension that allows you to specify the size of an array at runtime if the array is created on the stack. This is why, when you leave off the static
from the definition of x
, the code compiles. However, this would still not be legal in standard C.
The solution: Use a #define
.
Edit: Note that this is a point in which C and C++ differ. In C++, a const int
is a real compile-time constant and can be used to specify the size of arrays and the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With