Understanding the Ternary Operator in C++: How and When to Use It?

  • C/C++
  • Thread starter Raghav Gupta
  • Start date
  • Tags
    C++ Operator
In summary, the ternary operator is a switch that is functionally the same as the if statement. It can make your code hard to read if used to excess, but can be useful in some cases.
  • #1
Raghav Gupta
1,011
76
Member warned about posting questions that could be easily answered in a web search
What is ternary operator in c++ and its use?
 
Technology news on Phys.org
  • #2
It's used as a switch.

Code:
if (i == 10){
    return 5;
} else {
    return 1;
}

Is functionally the same as

Code:
return (i == 10) ? 5 : 1

The ? : set is the ternary operator: (bool ? ifTrue : ifFalse) will resolve to either ifTrue or ifFalse depending on the value of bool.

It's used for shorthand, or for a case where you want to alter the behavior of something based on something else inline. Practical example:
Code:
void printfString(const char * format, const char * str){
    printf(format, (str == NULL ? "NULL" : str));
}
 
  • #3
Have you used google?

First result with some pitfalls: http://www.cplusplus.com/forum/articles/14631/

It's usually applied in simple return statements.

for example this is how you could implement a max-function

C:
double fmax( double a, double b){
   return (a > b) ? a : b;
}

I would generally avoid using the ternary operation.
It can make your code hard to read.

Edit:
Too slow :)
 
  • #4
JorisL said:
I would generally avoid using the ternary operation.
It can make your code hard to read.

I so disagree. When used to excess or otherwise inappropriately, the ternary operator does indeed make ones code hard to read. However, when used correctly, the ternary operator makes ones code much more compact and much easier to read.

I have an ongoing disagreement with a vice president of the company I work for regarding the ternary operator. Yes, the ternary operator most certainly can be used in a way that can make ones code a good candidate for the IOCCC (the International Obfuscated C Code Contest). But then again, so can the dot operator:
Code:
// Don't do this.
foo().bar->baz(qux)->quux.quuux->quuuux();
Note well: The above violates the law of Demeter, aka the "don't talk to strangers" rule.

The easy rule is to ban the use of the dot operator, but nobody does that. So why are so many people so willing to ban the use of the ternary operator just because it can, when used to excess, make code hard to read?

The right rule, to me, is
  • Never use the ternary operator as an lvalue.
    Code:
    // Don't do this.
    (set_a ? a : b) = 42;
  • Don't chain the ternary operator.
    Code:
    // Don't do this.
    x = condition_a ?
      (condition_b ?
        (condition_c ? 0 : 1) : (condition_d ? 2 : 3)) ?
      (condition_e ? 4 : 5);
  • If it makes more sense to use an if statement, do so.
    Code:
    // I can't think of a good example. I like the ternary operator.
  • If it makes more sense to use the ternary operator, do so!
    Code:
    //Do this!
    std::cout << (success ? "Success!" ? "Failure.") << '\n';
 
Last edited:
  • Like
Likes newjerseyrunner and jim mcnamara
  • #5
D H said:
Never use the ternary operator as an lvalue.
Code:
// Don't do this.
(set_a ? a : b) = 42;

That's actually illegal unless both a and b are references, this would be the proper way to write that.
Code:
set_a ? (a = 42) : (b = 42);
But yeah, that's awful code.
 
  • #6
So I checked it out again in one of my books.
It gave some more examples and I agree, the notation is practical.

I guess it's a remnant of studying code only in my early teens.
A lot of resources strictly warned against, probably because they didn't want to write a longer post.
 
  • #7
newjerseyrunner said:
That's actually illegal unless both a and b are references, this would be the proper way to write that.
It is totally legal in C++, even if they aren't references. (The ternary operator in C isn't quite that powerful.)

Live demo: https://ideone.com/O7csXR

But just because it's legal doesn't mean you should use it.
 
Last edited:

1. What is a ternary operator in C++?

A ternary operator in C++ is a conditional operator that takes three operands and evaluates a condition. It is also known as the "conditional operator" or the "inline if statement". It is represented by the symbol "?" and is used to make decisions based on a condition.

2. What is the syntax of a ternary operator in C++?

The syntax of a ternary operator in C++ is: condition ? expression1 : expression2. The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed. The expressions can be any valid C++ expressions, including function calls, variables, or literal values.

3. What is the purpose of using a ternary operator in C++?

The purpose of using a ternary operator in C++ is to write concise and efficient code. It allows us to write conditional statements in a single line of code instead of using multiple lines with if-else statements. It also makes the code more readable and easier to understand.

4. Can a ternary operator be nested in C++?

Yes, a ternary operator can be nested in C++. This means that the expression used in the conditional statement can also be another ternary operator. However, it is recommended to use nested ternary operators sparingly as it can make the code more complex and difficult to read.

5. Are there any limitations to using ternary operators in C++?

Yes, there are a few limitations to using ternary operators in C++. Firstly, the expressions used must be of the same data type. Secondly, they cannot be used for complex conditionals that involve multiple comparisons or logical operators. Lastly, they should not be used for side-effect expressions, as the order of evaluation may not be as expected.

Similar threads

  • Programming and Computer Science
Replies
22
Views
1K
  • Programming and Computer Science
Replies
23
Views
2K
  • Programming and Computer Science
Replies
9
Views
607
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
4
Views
737
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
13
Views
3K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
  • Set Theory, Logic, Probability, Statistics
Replies
2
Views
952
Back
Top