Re: A bit off-topic (or gcc/ecgs bug?)

Ben Bridgwater (bennyb@ntplx.net)
Wed, 31 Mar 1999 21:24:20 -0500


Rivalino Matias Junior wrote:

> Hello All,
>
> I'm have a problem:
>
> #include <stdio.h>
>
> void main()
> {
> int x=0;
> int y=1;
>
> x= (y)?x=1:x=2;
> }
>
> The result of x is two. Why ?
>

The C /C++ standards define the behavior of the ?: conditional operator
as:

expr1 ? expr2 : expr3

expr1 is evaluated first, then if the value in non-zero expr2 is
evaluated and is the value of the expression, else expr3 is evaluated
and is the value of the expression. Note that only one of expr2 or expr3
is evaluated, which is important in a case where they have side effects
as in your example.

The operator precedence of ?: is higher than =, so the expression is
seen as:

x = ((y) ? x = 1 : x = 2)

First "(y)" is evaluated, and being non-zero, "x = 1" is then
evaluated (which has the side effect of assigning 1 to x), and becomes
the value of the conditional expression, which is then assigned to x.
The correct result is therefore x = 1.

Incidently, I tried this with the GNU and ecgs C/C++ compilers, and they
gave the correct result for C++, but complained "invalid lvalue in
assignment" for C. This seems to be a compiler bug.

If I added parenthesis to give "x = (y) ? (x = 1) : (x = 2)", then I got
the correct answer for C also.

If your compiler gives the result x = 2, then it is incorrect.

Ben

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.tux.org/lkml/