问题
I am confused between precedence of operators and want to know how this statement would be evaluated.
# include <stdio.h>
int main()
{
int k=35;
printf("%d %d %d",k==35,k=50,k>40);
return 0;
}
Here k
is initially have value 35, when I am testing k
in printf
I think :
k>40
should be checked which should result in 0k==35
should be checked and which should result in 1- Lastly 50 should get assigned to
k
and which should output 50
So final output should be 1 50 0
, but output is 0 50 1
.
回答1:
You can not rely on the output of this program since it is undefined behavior, the evaluation order is not specified in C since that allows the compiler to optimize better, from the C99
draft standard section 6.5
paragraph 3
:
The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
It is also undefined because you are accessing the value of k
and assigning to it in the same sequence point. From draft standard section 6.5
paragraph 2
:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
it cites the following code examples as being undefined:
i = ++i + 1;
a[i++] = i;
Update
There was a comment as to whether the commas in the function call acted as a sequence point or not. If we look at section 6.5.17 Comma operator
paragraph 2
says:
The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation.
but paragraph 3
says:
EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).
So in this case the comma does not introduce a sequence point.
回答2:
The order in which function arguments are evaluated is not specified. They can be evaluated in any order. The compiler decides.
回答3:
This is undefined behaviour.
You may get any value. Lack of sequence points in two consecutive execution. Increase strictness level for warning and you will get warning: operation on ‘k’ may be undefined
.
来源:https://stackoverflow.com/questions/18231716/c-programming-confusion-between-operator-precedence