Output: 6.7
cause
The declaration of x is inside foo but the initialization of x=5 happens outside of foo !
We need to understand that
static int x = 5;
it is not the same as
static int x; x = 5;
Other answers used important words here, scope and lifetime, and indicated that scope x is from the point of its declaration in the function foo to the end of the function foo . For example, I checked by moving the declaration to the end of the function, and this makes x undeclared in x++; expression.
Thus, the static int x (sphere) part of the statement actually applies when you read it, somewhere inside the function, and only from there forward, and not above it inside the function.
However, x = 5 (lifetime) part of the instruction is the initialization of the variable and the OUTSIDE function occurs as part of the program load. When the program loads, the variable x with the value 5 changes.
I read this in one of the comments: "In addition, this does not apply to the really confusing part, which is that the initializer is skipped on subsequent calls." It is skipped for all calls. Initialization of a variable outside the function’s own code.
The value 5 is theoretically set regardless of whether foo is called at all, although the compiler can optimize the function if you don't name it. The value 5 must be in the variable before foo is called.
Inside foo statement is static int x = 5; is unlikely to generate any code at all.
I found that the address x uses when I put the foo function in my program, and then (correctly) guessed that the same place would be used if I ran the program again. The partial screenshot below shows that x has a value of 5 before the first call to foo .

user3070485 Mar 05 '18 at 11:35 2018-03-05 11:35
source share