Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - On static a=c++, b++;+; What do you mean?
On static a=c++, b++;+; What do you mean?
I got the operator priority wrong just now. I'm sorry I misled you. Answer again:

A static variable means that although it is defined in a function, it will be like a global variable after definition. After the function is called, other variables in the function will disappear, but this static variable still exists.

(But static variables are still different from global variables. In a multi-file project, global variables can be used by all files, while static variables are only equivalent to global variables in this file and are not recognized in other files. But you don't need to know that much yet. )

The initial value of a static variable is assigned at compile time, not at function call time. In other words, when your program runs, C already has a value of 3. If the f () function is called many times, it will not assign the value to C again every time it is called, but let C keep the value unchanged. In other words, you can simply think of the above example as:

int c = 3; //Global variable c=3

Integer f (integer a)

{

int b = 0;

a=c++,b++; //c=3 when f () is called for the first time, and c=4 when it is called for the second time.

Return to a;

}

For a=c++,b++;

This sentence is a comma expression. The general form of comma expression is expr 1, expr2. It evaluates expr 1 and expr2 respectively, and then takes the value of expr2 as the value of the whole expression.

For this specific example, it evaluates the expressions a=c++ and b++ respectively, and then takes the value of b++ as the value of the whole expression.

Here, because the priority ratio of = is high, the whole expression is equivalent to (a=c++), b++;+; Not equivalent to a=(c++, b++);

When f () is called for the first time, the expression a=c++ is executed first, and the result is as follows:

Assign the value of C to A, and then C itself increases 1, so the result is A = 3 and C = 4.

Then the expression b++ is executed, and after execution, b= 1, which is also the value of the whole comma expression, but this value is not used.

This function returns the value of a, which is 3.

When f () is called for the second time, the expression a=c++ is executed first, and the result is as follows:

Assign the value of C (which has become 4 at this time) to A, and then C itself increases by 1, so the result is A = 4 and C = 5.

Then the expression b++ is executed, and after execution, b= 1, which is also the value of the whole comma expression, but this value is not used.

This function returns the value of a, which is 4.

So the final output is 4.