🌐
Sub-Etha Software
subethasoftware.com › 2016 › 12 › 09 › nested-ternary-operators-in-c
Nested ternary operators in C | Sub-Etha Software
June 4, 2024 - https://en.wikipedia.org/wiki/Ternary_conditional_operator#C · It is a great shortcut for response strings. For instance, turning a boolean true/false result in to a string: printf( "Status: %s\n", (status == true ? "Enabled" : "Disabled" ); This will print “Status: Enabled” if status==true, or “Status: Disabled” if status==false. What a neat shortcut. Recently, I saw a nested use of this ternary operator.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › c-nested-ternary-operator
C++ | Nested Ternary Operator - GeeksforGeeks
July 11, 2025 - Expression using Ternary operator: ... // C++ program to illustrate // nested ternary operators #include <bits/stdc++.h> using namespace std; int main() { cout << "Execute expression using" << " ternary operator: "; // Execute expression using // ternary operator int a = 2 > 5 ?
People also ask

What is a Ternary Operator in C?
The ternary operator in C is a conditional operator used to evaluate expressions. It takes three operands: a condition, a result if true, and a result if false. It’s written as condition ? true_result : false_result.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › c ternary operator
Ternary Operator in C: A Complete Guide
Is the Ternary Operator efficient in C?
Yes, the ternary operator can improve code efficiency by condensing conditional statements into a single line. However, when used excessively or in complex conditions, it might make code less readable and harder to maintain.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › c ternary operator
Ternary Operator in C: A Complete Guide
What is the syntax of the Ternary Operator in C?
The syntax of the ternary operator in C is: condition ? expression_if_true : expression_if_false; It first evaluates the condition, and depending on the result, it executes one of the two expressions.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › c ternary operator
Ternary Operator in C: A Complete Guide
🌐
freeCodeCamp
freecodecamp.org › news › c-ternary-operator
Ternary Operator in C Explained
January 20, 2020 - Ternary operators can be nested just like if-else statements.
🌐
CodeSpeedy
codespeedy.com › home › nested ternary operator in c++
Nested Ternary Operator in C++ - CodeSpeedy
June 21, 2020 - #include <iostream> using namespace std; int main() { int a,b,c,ans; std::cout<<"Enter the first number : "; std::cin>>a; std::cout<<"Enter the second number : "; std::cin>>b; std::cout<<"Enter the third number : "; std::cin>>c; ans = (a>b) ? ( a>c ? a : c) : ( b>c ? b : c); //nested ternary operator to calculate highest among 3 nos.
🌐
Unstop
unstop.com › home › blog › ternary (conditional) operator in c (+code examples)
Ternary (Conditional) Operator In C (+Code Examples)
December 26, 2023 - Now, if the outer condition is true, we move to the inner condition num % 2 == 0, which determines if the number is even or odd. If the number is, in fact, even, then we assign the phrase- Even number to the result variable. If the number is odd, then the program assigns the phrase- Odd number to the result. After the evaluation of the nested ternary operator, we use the pintf() function to display the value of the result to the console.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › c ternary operator
Ternary Operator in C: A Complete Guide
October 14, 2024 - The ternary operator is used to evaluate the condition (num > 0). If the condition is true, "Positive" is printed. If the condition is false, it checks if (num < 0) to print "Negative".
🌐
BeginnersBook
beginnersbook.com › 2022 › 09 › conditional-ternary-operator-in-c-with-examples
Conditional (Ternary) Operator in C with Examples
We can have a ternary operator inside another ternary operator. This is called nesting of conditional operators.
Find elsewhere
🌐
Educative
educative.io › answers › how-to-use-the-nested-ternary-operator-in-cpp
How to use the nested ternary operator in c++
We will show the syntax of attaining the functionality of nested if, and else-if separately below. condition1 ? conditon2 ? Code_Block1: Code_Block2 : Code_Block3 ... The syntax shows that if condition1 is true, then check condition2, else execute Code_Block3. If condition2 is true, then the Code_Block1 is executed, else Code_Block2 gets executed. ... The syntax shows that if condition1 is true, then Code_Block1 gets executed, else condition 2 is checked.
Top answer
1 of 7
71

The statement as written could be improved if rewritten as follows....

good = m_seedsfilter==0 ? true :
       m_seedsfilter==1 ? newClusters(Sp) :
                          newSeed(Sp);

...but in general you should just become familar with the ternary statement. There is nothing inherently evil about either the code as originally posted, or xanatos' version, or mine. Ternary statements are not evil, they're a basic feature of the language, and once you become familiar with them, you'll note that code like this (as I've posted, not as written in your original post) is actually easier to read than a chain of if-else statements. For example, in this code, you can simply read this statement as follows: "Variable good equals... if m_seedsfilter==0, then true, otherwise, if m_seedsfilter==1, then newClusters(Sp), otherwise, newSeed(Sp)."

Note that my version above avoids three separate assignments to the variable good, and makes it clear that the goal of the statement is to assign a value to good. Also, written this way, it makes it clear that essentially this is a "switch-case" construct, with the default case being newSeed(Sp).

It should probably be noted that my rewrite above is good as long as operator!() for the type of m_seedsfilter is not overridden. If it is, then you'd have to use this to preserve the behavior of your original version...

good = !m_seedsfilter   ? true :
       m_seedsfilter==1 ? newClusters(Sp) :
                          newSeed(Sp);

...and as xanatos' comment below proves, if your newClusters() and newSeed() methods return different types than each other, and if those types are written with carefully-crafted meaningless conversion operators, then you'll have to revert to the original code itself (though hopefully formatted better, as in xanatos' own post) in order to faithfully duplicate the exact same behavior as your original post. But in the real world, nobody's going to do that, so my first version above should be fine.


UPDATE, two and a half years after the original post/answer: It's interesting that @TimothyShields and I keep getting upvotes on this from time to time, and Tim's answer seems to consistently track at about 50% of this answer's upvotes, more or less (43 vs 22 as of this update).

I thought I'd add another example of the clarity that the ternary statement can add when used judiciously. The examples below are short snippets from code I was writing for a callstack usage analyzer (a tool that analyzes compiled C code, but the tool itself is written in C#). All three variants accomplish exactly the same objective, at least as far as externally-visible effects go.

1. WITHOUT the ternary operator:

Console.Write(new string(' ', backtraceIndentLevel) + fcnName);
if (fcnInfo.callDepth == 0)
{
   Console.Write(" (leaf function");
}
else if (fcnInfo.callDepth == 1)
{
   Console.Write(" (calls 1 level deeper");
}
else
{
   Console.Write(" (calls " + fcnInfo.callDepth + " levels deeper");
}
Console.WriteLine(", max " + (newStackDepth + fcnInfo.callStackUsage) + " bytes)");

2. WITH the ternary operator, separate calls to Console.Write():

Console.Write(new string(' ', backtraceIndentLevel) + fcnName);
Console.Write((fcnInfo.callDepth == 0) ? (" (leaf function") :
              (fcnInfo.callDepth == 1) ? (" (calls 1 level deeper") :
                                         (" (calls " + fcnInfo.callDepth + " levels deeper"));
Console.WriteLine(", max " + (newStackDepth + fcnInfo.callStackUsage) + " bytes)");

3. WITH the ternary operator, collapsed to a single call to Console.Write():

Console.WriteLine(
   new string(' ', backtraceIndentLevel) + fcnName +
   ((fcnInfo.callDepth == 0) ? (" (leaf function") :
    (fcnInfo.callDepth == 1) ? (" (calls 1 level deeper") :
                               (" (calls " + fcnInfo.callDepth + " levels deeper")) +
   ", max " + (newStackDepth + fcnInfo.callStackUsage) + " bytes)");

One might argue that the difference between the three examples above is trivial, and since it's trivial, why not prefer the simpler (first) variant? It's all about being concise; expressing an idea in "as few words as possible" so that the listener/reader can still remember the beginning of the idea by the time I get to the end of the idea. When I speak to small children, I use simple, short sentences, and as a result it takes more sentences to express an idea. When I speak with adults fluent in my language, I use longer, more complex sentences that express ideas more concisely.

These examples print a single line of text to the standard output. While the operation they perform is simple, it should be easy to imagine them as a subset of a larger sequence. The more concisely I can clearly express subsets of that sequence, the more of that sequence can fit on my editor's screen. Of course I can easily take that effort too far, making it more difficult to comprehend; the goal is to find the "sweet spot" between being comprehensible and concise. I argue that once a programmer becomes familiar with the ternary statement, comprehending code that uses them becomes easier than comprehending code that does not (e.g. 2 and 3 above, vs. 1 above).

The final reason experienced programmers should feel comfortable using ternary statements is to avoid creating unnecessary temporary variables when making method calls. As an example of that, I present a fourth variant of the above examples, with the logic condensed to a single call to Console.WriteLine(); the result is both less comprehensible and less concise:

4. WITHOUT the ternary operator, collapsed to a single call to Console.Write():

string tempStr;
if (fcnInfo.callDepth == 0)
{
   tempStr = " (leaf function";
}
else if (fcnInfo.callDepth == 1)
{
   tempStr = " (calls 1 level deeper";
}
else
{
   tempStr = " (calls " + fcnInfo.callDepth + " levels deeper";
}
Console.WriteLine(new string(' ', backtraceIndentLevel) + fcnName + tempStr +
                  ", max " + (newStackDepth + fcnInfo.callStackUsage) + " bytes)");

Before arguing that "condensing the logic to a single call to Console.WriteLine() is unnecessary," consider that this is merely an example: Imagine calls to some other method, one which takes multiple parameters, all of which require temporaries based on the state of other variables. You could create your own temporaries and make the method call with those temporaries, or you could use the ternary operator and let the compiler create its own (unnamed) temporaries. Again I argue that the ternary operator enables far more concise and comprehensible code than without. But for it to be comprehensible you'll have to drop any preconceived notions you have that the ternary operator is evil.

2 of 7
27

The equivalent non-evil code is this:

if (m_seedsfilter == 0)
{
    good = true;
}
else if (m_seedsfilter == 1)
{
    good = newClusters(Sp);
}
else
{
    good = newSeed(Sp);
}

Chained ternary operators - that is, the following

condition1 ? A : condition2 ? B : condition3 ? C : D

- are a great way to make your code unreadable.

I'll second @phonetagger's suggestion that you become familiar with ternary operators - so that you can eliminate nested ones when you encounter them.

🌐
Quora
quora.com › Is-using-nested-ternary-statements-a-bad-practice
Is using nested ternary statements a bad practice? - Quora
Answer (1 of 9): Definitely, but so is avoiding ternaries altogether. Consider this seahorse: Oh no, actually I meant this one: Now, someone fed up with all that would probably become overzealous and write this: [code]def processor(x) x.is_a?(String) ? x.length : (x.is_a?(Numeric) ? (x > 1 ...
🌐
Cplusplus
cplusplus.com › forum › articles › 14631
How to use the Conditional (ternary) operator
Just to add an opinion to an otherwise ... the ternary operator: 1) To condense what would be at least 4 lines of code (depending upon your coding standards) to 1. (Bad) example, but illustrates the point: 2) To increase maintainability by eliminating duplicate code. Contrived example: Note above there is now only one call to some_function() instead of two, eliminating the duplicate parameter list. Nesting ternary operators ...
Top answer
1 of 2
3

C is defined by a language grammar; a precedence table is a handy condensing of the grammar into something that humans can take in at a glance, but it doesn't exactly correspond to what the grammar specifies.

You may need to consult the language grammar in order to resolve associativity around a ternary operator. Personally I always explicitly use parentheses so that a reader who's not a language lawyer can still understand what's going on (and so that I don't make mistakes).

An example is:

c ? c = a : c = b

which must be parsed as

(c ? c = a : c) = b

which is illegal in C, since the ternary operator does not give an lvalue. Incidentally, the C++ grammar is different; in that language this is parsed as

c ? c = a : (c = b)

which is legal; and also the ternary operator can give an lvalue in C++.

In your case, the question is which of the following it is:

Z = ((i , j) ? X : Y)
Z = (i , (j ? X : Y))
(Z = i, j) ? X : Y
(Z = i), (j ? X : Y)

I believe the latter is correct here, so you should end up with j = i plus an expression with no side-effect.

2 of 2
3

What you have here is hopefully code you have read and you want to get rid of, not code you actually use.

You have a combination of two unparenthesed ternay operators and two uses of the comma operator.

Despite no use of parentheses, the nesting of ?: is unambiguous:

a ? b ? c : d : e

can only mean

a ? ( b ? c : d) : e

as there is no other way to interpret it.

The 2nd comma operator is in parentheses, so it is unambiguous as well.

The only point of doubt is the comma operator at the start, where you might want to consult a precedence table.

Here we see that , has the lowest precedence and thus we have

(j = i), (j ?  (i, j) ? i : j : j);

which is a comma operator with an assignment as first expression and an unevaluated other expression as second expression, which is the result.

In short, if we omit the right side, which isn't used nevertheless, we just have j = i, but this expression lacks unreadability.

So the output is 10 10.

Great trap, this expression... but as it is written, the answer doesn't cover this. If I erroneously evaluated it as j = j ? i : j; I would get 10 10 as well.

🌐
Hero Vired
herovired.com › learning-hub › topics › ternary-operator-in-c
Ternary Operators in C : Examples and Syntax - Hero Vired
In this section, we will learn about the nested ternary operator in the C language and find the largest number in three variables. The following program demonstrates the Nested Ternary Operator · Progarm · #include<stdio.h> void main() { int a =30, b = 50, c = 100, larg; larg = (a>b)?((a>c)?a:c):((b>c)?b:c); printf("Largest number is: %d", larg); } Output ·
🌐
Wikipedia
en.wikipedia.org › wiki › Ternary_conditional_operator
Ternary conditional operator - Wikipedia
January 27, 2026 - In R—and other languages with literal expression tuples—one can simulate the ternary operator with something like the R expression c(expr1,expr2)[1+condition] (this idiom is slightly more natural in languages with 0-origin subscripts). Nested ternaries can be simulated as c(expr1,expr2,expr3)[which.first((c(cond1,cond2,TRUE))] where the function which.first returns the index of the first true value in the condition vector.
🌐
TutorialsPoint
tutorialspoint.com › home › cprogramming › c ternary operator
C Ternary Operator
June 10, 2012 - Just as we can use nested if-else statements, we can use the ternary operator inside the True operand as well as the False operand.
🌐
Medium
medium.com › @benlmsc › stop-using-nested-ternary-operators-heres-why-53e7e078e65a
Stop using nested ternary operators. Here’s why. | by Ben Lmsc | Medium
February 12, 2023 - It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.
🌐
Scribd
scribd.com › document › 463735146 › C-Nested-Ternary-Operator
C++ - Nested Ternary Operator | PDF
Please check your connection, disable any ad blockers, or try using a different browser.
🌐
Codecademy
codecademy.com › forum_questions › 4f2343035ed3e90001012641
Can you create a nested ternary operator? | Codecademy
I always prefer using if statements, they have a nice structure to them and are very intuitive if you use {} and indent each nested if. ... it’s also good to space out the binary operators like necro did. I actually space out after the parenthesis too. if ( i < n ) { etc etc ... I am learning JavaScript right now, but if my memory serves correctly for C# you cannot use ternary operators for nested if statments.