2
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Narue
0

That code shouldn't compile at all, much less output the wrong value. Try this program and see if you get the same erroneous output:

#include <stdio.h>

int main(void)
{
    int a = 10, b;

    b = (a >= 5) ? 100 : 200;

    printf("%d\n", b);

    return 0;
}
0

this program does compile. but i dont understand what's wrong with the code. Your program gives 100

0

this program does compile

What compiler are you using? It's either broken or you're relying on an extension.

but i dont understand what's wrong with the code.

It's a syntax error, and your compiler is incorrect in allowing it. But in allowing it, the expression is being parsed like so:

b = ((a >= 5) ? (b = 100) : b) = 200;

a is greater than 5, so b is set to 100, then the ternary expression evaluates to b (the result of b = 100 ), which is then assigned a value of 200. Thus the end result of the expression is that b is set to 200.

However, the ternary operator does not result in an lvalue, so assigning 200 to it is illegal. That's why your compiler is doing the wrong thing.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.