Disclaimer:
C/C++
double tag, because I tested the bit of code on both C and C++ and it is just 4 lines of code (and the only difference is that gcc/clang
give a warning while g++/clang++
give an error.)Background:
In replying to another question, I started to think about why the OP can not modify a public static
variable. I thought about it a bit and then reduced the problem a bit further, where I can see the same effect, but without needing any class or static member variables.
Question: Then the following code can reproduce the observation.
int global_n; // I know it can be initialized right away here also: int global_n = 1;
global_n = 2; // This does not compile in C++. In C it gives a warning about missing type-specifier
int main() {
global_n = 2; // This does compile in both C/C++ of course
}
Which brings me to my question: Global variables (and hence static
variables/member-variables) can only be initialized, directly there when they are declared. But any subsequent modifications can only occur inside a function. Correct?
Any specific reason for this?
Outside of a function, you cannot have statements (i.e. executable lines of code), only declarations and definitions.
In the case of global_n = 2;
at global scope, C90 has a legacy feature that if a variable is declared without a type then the has a default type of int
(C99 removed the feature and requires a type). That's what's happening in this case, and that's also why you get a warning about the type missing.
C++ doesn't have that rule, so this appears as a statement outside of a function which is an error.