Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay...This problem is driving me crazy...
but the code is pretty easy, and I did already google it.

Code :

C++
void f(int c) {
	static int foo = c;
}


Here is what I googled"ed"

Difference between static in C and static in C++?? - Stack Overflow[^]

It says static in C is 'equalvalent to' C++.
but my compiler just keep saying

"Initializer element is not constant"

and also I did google it, it just keeps saying the 'constant' problem....
but 'const' is not what I want, I just need to reserve the variable 'foo' !

What I have tried:

Google
Posted
Updated 2-Jan-17 16:08pm
v4

Statics are more "similar" than "equivalent" between C/C++....

Here's an explanation of what you're seeing:
Initialization of static variables in C - GeeksforGeeks[^]

The initialization order in C means that the static must be defined from a constant (it doesn't imply that the value has to remain constant). This requirement isn't in C++ because order of initialization is a bit different in C++ and static no longer get initialized before "main" but rather the first time they're encountered (for statics in the body of a function anyway).
 
Share this answer
 
Comments
nv3 2-Jan-17 19:02pm    
5.
Member 12928053 2-Jan-17 22:08pm    
Thank you so much for this explanation.
It help me a lot, God...Finally I solve this problem.
btw My second exmaple definitely wrong, I forgot to check the init.
The error message is clearly telling you what is wrong. You are trying to initialise a static constant from a value that is not known at compile time.
 
Share this answer
 
With C, static variables can be only initialised with constant values but function parameters are not constant.

The solution is quite simple in your case. Split the command into an initialisation and an assignment:
void f(int c) {
    static int foo = 0;
    foo = c;
}
 
Share this answer
 
Comments
Albert Holguin 2-Jan-17 16:02pm    
This would compile...except that this wouldn't give you the expected results... because the value of foo would get initialized to c every time f() was called and not only the first time.
Jochen Arndt 2-Jan-17 17:00pm    
As with C++ and requested by the comment of his second example:
"'foo' should be always equal to 'bar'"

A common solution for first call initialisation is initialising with a reserved value like -1:

static int foo = -1;
if (-1 == foo) foo = c;
Albert Holguin 2-Jan-17 17:04pm    
Yeah, OP had conflicting information, I *THINK* he meant foo should be equal to bar on the first iteration only.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900