retagged by
575 views
0 votes
0 votes

P1:

int main()
{
int a,b,c;
a = 10;
a>=5? b=100 : b=200;
printf("%d %d",a,b);
    return 0;
}

P2:

int main()
{
int a,b,c;
a = 10;
a>=5? b=100 : (b=200);
printf("%d %d",a,b);
    return 0;
}

P1 gives error as

lvalue required as left operand of assignment
 a>=5? b=100 : b=200;
                ^

while P2 doesn't!

Please explain why?

retagged by

1 Answer

Best answer
2 votes
2 votes

precedence of RELATIONAL OPERATOR> TERNARY OPERATOR > ASSIGNMENT OPERATOR

therefor in our case evaluation order should be (>=) first the (?:) then (=)

according to this order of precedence ,  in P1 , expression a>=5? b=100 : b=200;  is evaluated as

((a>=5)?b=100:b)=200 which is invalid because lefthand side should be a variable to store 200 hence ur getting error of lvalue required. while this is not an issue in P2

selected by

Related questions

0 votes
0 votes
1 answer
1
Debargha Mitra Roy asked 3 days ago
48 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...
0 votes
0 votes
2 answers
3
Debargha Mitra Roy asked Apr 10
103 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
1 votes
1 votes
1 answer
4
SSR17 asked Feb 29
252 views
#include <stdio.h int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }output is 255 , but please explain how