Ternary operator if I avoid writing expression 2 it works but if I not write expression 3 it gives an error duplicate

0 votes

Code

#include<iostream>

int main()
{
    int a=4,b,c;
    a==3 ? : b=a*a ;     // Works fine
    a==4 ? c=a*a : ;     // ERROR Expected Primary expression before ;
}

1st conditional statement

 I did not write 'Expression 2' but it will not produce error 

2nd Conditional statement

 I did not write 'Expression 3' it gives an error 

so why it is differentiating in 'Expression 2' and 'Expression 3' ?


Jun 28, 2022 in C++ by Nicholas
• 7,760 points
2,219 views

1 answer to this question.

0 votes
6.8 Conditionals with Missing Opponents

In a conditional statement, the middle operand might be omitted.

If the first operand is nonzero, the value of the conditional expression is returned.

As a result, the expression

x ?: y

If x is nonzero, it has the value of y; otherwise, it has the value of x.

This example is exactly the same as

x ? x: y

The option to omit the middle operand is not really beneficial in this basic scenario.

When the first operand has or may have a side effect (if it is a macro parameter), it becomes beneficial.

The side effect would then be performed twice by repeating the operand in the middle.

By omitting the middle operand, the previously computed value is used without the unwanted implications of recomputing it.
answered Jun 28, 2022 by Damon
• 4,960 points

Related Questions In C++

0 votes
1 answer

Is 'If Else' statement indentation important or not in C++? [duplicate]

White space has no effect on the understanding of code in C and C++.  That is not to say that the programmer should be unconcerned about its misuse. The easiest method to demonstrate what the above code truly represents is to specify all of the inferred braces directly, as seen below.  The 'if then' or 'otherwise' clause only affects one line of code in the if statement with no brackets. This is one of the reasons why people strive to insis