Home >Backend Development >C++ >How Does the Conditional Operator Function Differ Between C and C ?
The Conditional Operator in C versus C
The conditional operator (?) in C exhibits subtle distinctions from its counterpart in C, particularly in its ability to return an lvalue.
Returning an Lvalue
In C , the conditional operator can return an lvalue, which is a variable or expression that can be assigned to. This allows for operations like:
<code class="c++">(true ? a : b) = 1;</code>
In this example, the variable a is assigned a value of 1 if the condition true is true.
In contrast, C does not permit lvalues to be returned by the conditional operator. To achieve a similar effect, one must use if/else statements or directly manipulate references:
<code class="c">*(true ? &a : &b) = 1;</code>
Operator Precedence
Additionally, C 's conditional operator has equal precedence with the assignment operator (=) and groups right-to-left. This means code like:
<code class="c++">true ? a = 1 : b = 2;</code>
is valid. However, in C, without parentheses enclosing the last expression:
<code class="c">true ? a = 1 : (b = 2);</code>
an error will occur.
The above is the detailed content of How Does the Conditional Operator Function Differ Between C and C ?. For more information, please follow other related articles on the PHP Chinese website!