0
int a = 2, b = 3, c = 4, d = 5;
a > 1 ? b : c = d;

One my friend told me that this invoked undefined behavior and I feel like the opposite. Can anyone help me?

porker2008
  • 23
  • 3

2 Answers2

1

If to write the operator like

( a > 1 ? b : c ) = d;

(because in this way it is parsed in C) then it is valid in C++ but will not be compiled in C because in C the operator returns rvalue.

If to remove the parentheses then in C++ it will be equivalent to

a > 1 ? b : ( c = d );

Thus the operator behaves differently in C and C++. In C record

a > 1 ? b : c = d;

is equivalent to

( a > 1 ? b : c ) = d;

and will not be compiled.

In C++ record

a > 1 ? b : c = d;

is equivalent tp

a > 1 ? b : ( c = d );

and will be compiled.

Moreover if to rewrite it in C++ in the same way as it is parsed in C

( a > 1 ? b : c ) = d;

then again it will be compiled because the operator in C++ returns lvalue.

Here is the definition of the operator in C

conditional-expression:
       logical-OR-expression
       logical-OR-expression ? expression : conditional-expression

and here is the definition of the operator in C++

conditional-expression:
       logical-or-expression
       logical-or-expression ? expression : assignment-expression

As you can see that apart from the semantic difference there is a difference in the grammar of the operator relative to the third expression.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

This code will not invoke undefined behavior but will produce some error in C as a > 1 ? b : c = d; will be evaluated as

(a > 1 ? b : c) = d;  

a > 1 ? b : c will result in an rvalue which can't be a left operand of assignment operator =.

haccks
  • 104,019
  • 25
  • 176
  • 264