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

  • Context: C/C++ 
  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    C++ Operator
Click For Summary

Discussion Overview

The discussion revolves around the ternary operator in C++, exploring its functionality, usage, and implications for code readability. Participants share examples and personal experiences regarding when and how to use the operator, as well as potential pitfalls associated with its use.

Discussion Character

  • Debate/contested
  • Technical explanation
  • Conceptual clarification

Main Points Raised

  • Some participants describe the ternary operator as a shorthand for conditional statements, providing examples of its use in return statements and function parameters.
  • Others express caution, arguing that the ternary operator can make code harder to read, especially when overused or misapplied.
  • One participant shares a personal disagreement with a colleague regarding the appropriateness of the ternary operator, suggesting that it can be both compact and clear when used correctly.
  • Concerns are raised about specific misuse of the ternary operator, such as using it as an lvalue or chaining multiple ternary operations, which can lead to confusing code.
  • Some participants note that while the ternary operator is legal in C++, its legality does not imply that it is advisable to use in all contexts.
  • References to external resources and personal experiences with learning and using the ternary operator are shared, indicating varying levels of comfort and understanding among participants.

Areas of Agreement / Disagreement

Participants express differing views on the use of the ternary operator, with some advocating for its use in certain contexts while others caution against it due to potential readability issues. The discussion remains unresolved regarding the best practices for using the ternary operator.

Contextual Notes

Participants mention specific coding practices and rules regarding the ternary operator, highlighting that its appropriateness can depend on context and personal coding style. There are references to legal versus advisable use, indicating a nuanced understanding of the operator's functionality.

Raghav Gupta
Messages
1,010
Reaction score
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
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));
}
 
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 :)
 
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   Reactions: newjerseyrunner and jim mcnamara
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.
 
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.
 
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:

Similar threads

  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 13 ·
Replies
13
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 12 ·
Replies
12
Views
4K
Replies
53
Views
5K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K