I\'m curious why the following code snippet doesn\'t compile:
typedef struct Foo {
int a;
int b;
} Foo;
static const Foo FooZero = { 0, 0 };
typedef s
In the C language a const
or static const
value is not considered a "compile time constant", whereas
#define FooZero {0, 0}
is considered to be a compile-time constant. You may say "But but, it even says const
! How can it not be a constant??" And indeed the language says you cannot change the value of a thing you specify as const
, but you also cannot use it as an initializer. You can ask why all you like, it won't change how the language defines it - although your compiler may give you an option to change this behaviour, and it is not too hard to work around in any case.
I think it is quite common for C compilers to treat static constants like global variables - that is, to actually allocate space for a variable (which never changes), rather than program the hard values into the machine code as it would if you did a #define
. In this case the constants, indeed as the compiler says, are not compile-time constants, although they are constants for all other purposes after they are initialised (at runtime).