问题
int get()
{
static i = 1;
return i++;
}
int main(int argc, char *argv[])
{
printf("%d %d %d\n", get(), get(), get());
return 0;
}
Output: 3 2 1 (Order depends upon compiler)
Question: But why is the value before increment returned of the static variable (file scope). What is the thumb rule of post/pre increment? I never get it correct. Please help.
Okay, let me be more specific, all the examples that I read are like, a = i++; or a = ++i;
these are the expressions to increment then assign or assign then increment. But what kind of expressions are these, return i++; func(a++);
I read it like this "after i++ nothing to assign, so return the final incremented value" (correct me here)
回答1:
There are two issues here, lifetime and scope.
The scope of variable is where the variable name can be seen. Here, i is visible only inside function get().
The lifetime of a variable is the period over which it exists. If i were defined without the keyword static, the lifetime would be from the entry into get() to the return from get(); so it would be re-initialized to 1 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the program; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to get().
Difference between post and pre increment: What is the difference between pre-increment and post-increment in the cycle (for/while)?
Source: Answer at this place
Update 1
Post increment works by making a temporary copy of the existing value, then incrementing the original value, then finally returning the temporary as a result of the expression. As a result, it appears the increment is done post-expression evaluation, but it isn't, and a sample program demonstrating this is fairly straight forward if interested. It is the temp-copy that makes post-inc expensive. (Thanks to WhozCraig for correcting)
Update 2
Both of those are post-increment unary operations. Both of them make a temp copy of the operand (i in the first case, a in the second), then increment the operand, then return the temp copy as the result of the post-inc expression. The result in the first case is i is incremented and its value prior to the increment is returned. In the second case a is incremented and func is invoked with the value prior to the increment.(Given by WhozCraig)
来源:https://stackoverflow.com/questions/21808791/regarding-post-increment