Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator differences between C and C++

I read somewhere that the ?: operator in C is slightly different in C++, that there's some source code that works differently in both languages. Unfortunately, I can't find the text anywhere. Does anyone know what this difference is?

like image 771
rlbond Avatar asked Jul 04 '09 17:07

rlbond


People also ask

What are different types of conditional operator in C?

In the C programming language the operators are classified as unary, binary, and ternary based on the number of operands they require.

What do you mean by conditional operator in C?

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'. As conditional operator works on three operands, so it is also known as the ternary operator.

Which operator in C is called a conditional operator?

In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c .


1 Answers

The conditional operator in C++ can return an lvalue, whereas C does not allow for similar functionality. Hence, the following is legal in C++:

(true ? a : b) = 1; 

To replicate this in C, you would have to resort to if/else, or deal with references directly:

*(true ? &a : &b) = 1; 

Also in C++, ?: and = operators have equal precedence and group right-to-left, such that:

(true ? a = 1 : b = 2); 

is valid C++ code, but will throw an error in C without parentheses around the last expression:

(true ? a = 1 : (b = 2)); 
like image 140
goldPseudo Avatar answered Sep 29 '22 06:09

goldPseudo