int a=10,b;
b=(a>=5)?b=100:b=200;
printf("%d",b)


why does the output shows as 200? Plz explain

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;
}

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.