(e-mail address removed) said:
Hello,
I would appreciate some comments about the piece of code given below
and explanation about the result of this specified code.
int x = 20;
printf("%d %d %d",x < 30, x = 40; x > 10);
The output of these code will be :: 0 40 1
Well, it might be, once you wrap a program around it and fix the syntax
error (a semicolon instead of a comma). First, I'll explain why you might
get that output, and then I'll explain why you might not.
x < 30 is a relational expression, and all expressions have values.
Relational expressions have the value 0 if they're false, and 1 if they're
true. So x < 30 will evaluate to 0 if x is less than 30, and 1 otherwise.
x = 40 is an assignment expression, and its value is the same as the value
taken by its left operand. So the value of (x = 40) is 40.
x > 10 works the same way - i.e. relationally - as x < 30. That is, if the
expression is false, the value yielded is 0. Otherwise, it's 1.
Now that would suggest an output of 1 40 1, wouldn't it? But C doesn't
specify the order in which function argument expressions are evaluated,
and it would appear that on this occasion your implementation has decided
to evaluate from right to left. Thus, x starts at 20, the x > 10 is then
evaluated and yields 1 (which will be printed last), then x becomes 40,
and then x is tested against 30 - since it's greater (because it has
become 40), x < 30 is false, which gives 0. And that's why you're getting
0 40 1 instead of 1 40 1.
But in fact, you're breaking a C rule:
"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 accessed only to
determine the value to be stored."
There is no sequence point between any of the function argument
evaluations, and you're fetching the value of x not only to modify it, but
also to compare against other information. This isn't a syntax error or a
constraint violation, so the compiler is not required to display a
diagnostic message, but it nevertheless violates a "shall" clause, and
therefore the behaviour of the program is undefined.
The fix is as follows:
x = 20;
printf("%d ", x < 30);
printf("%d ", x = 40);
printf("%d", x > 10);
C is such a flexible language that it's tempting to take too much advantage
of that flexibility. Resist the temptation!