I'm new to C and today I learnt "?" operator which is the short type of if-else statement. However, when I execute this code:
int b;
int x;
b=3<2?x=12:x=34;
int b;
int x;
b=3<2?x=12:(x=34);
+1 for interesting question - it highlights two differences between C++ and C.
(1) The evaluation rules for ternary expressions are different in C and C++
C++ parses as follows
logical-OR-expression ? expression : assignment-expression
It is therefore parsing your statement by matching assignment-expression
to x=34
b = 3<2 ? x = 12 : (x = 34);
But C parses like this
logical-OR-expression ? expression : conditional-expression
x = 34
is not a conditional-expression
so your statement gets parsed like
b = (3<2 ? x = 12 : x) = 34;
(2) The conditional operator in C++ can return an lvalue
, whereas C cannot. Hence, the following is legal in C++ but not in C:
b = (3<2 ? x = 12 : x) = 34;
Verified on ideone.com for C and C++ compilers. See also these links Errors using ternary operator in c for diff between C and C++ ternary operator Conditional operator differences between C and C++ for diff in lvalue rules