Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using static const instead of #define?

Tags:

c

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 ofx' 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?

like image 589
Simon Elliott Avatar asked Sep 25 '09 11:09

Simon Elliott


1 Answers

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.

like image 173
Martin B Avatar answered Sep 28 '22 16:09

Martin B