I was disappointed to learn recently that C does not allow assignment of variables during static variable initialization, unlike C++. E.g. the following code compiles as C++...
#include <stdio.h>
int foo()
{
return 1;
}
static int g_i = foo();
int main( int argc, char* argv[] )
{
printf( "%d\n", g_i );
return 0;
}
...but issues the following error with a C compiler:
>cc -g main.c
main.c:8:1: error: initializer element is not constant
static int g_i = foo();
^
I thought I could be clever by using the comma operator a-la:
static int g_i = ( foo(), 1 );
...but the compiler seemed unimpressed with my attempted cleverness, and output effectively the same error:
>cc -c main.c
main.c:8:1: error: initializer element is not constant
static int g_i = ( foo(), 1 );
^
:(
Q: Why does use of the comma operator not work? I may be unaware of some subtlety, but my understanding led me to think it should have worked: the C
compiler is demanding g_i
be initialzed to a compiletime constant; supposedly the comma operator would have offered me evaluation of the code left of the comma, but assignment of the code right of the comma, which is a compiletime constant.
Q: Are there any hacks - I don't care how dirty - that would allow assignment to g_i
the return value of foo()
to g_i
?
This is a simplified representation of a C
program where I really just want to call a function before main()
- I don't care about the return value, but it's a more complicated problem to call a void
function before main()
, which I would rather sidestep altogether by using an int
function whose value is assigned to a throwaway static int
variable.