Using Ternary Operator in C for If Else & Else If

  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Operator
Click For Summary

Discussion Overview

The discussion revolves around the use of the ternary operator in C programming, specifically regarding its application for constructing if-else and else-if statements. Participants explore the feasibility and readability of using nested ternary operators compared to traditional if statements.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Conceptual clarification

Main Points Raised

  • Some participants suggest that nested ternary operators can be used to handle multiple conditions, but caution that they may reduce readability.
  • One participant proposes using user-defined functions to encapsulate conditions and results, which could mimic the ternary operator's functionality but might complicate the code.
  • Examples are provided showing how to implement multiple conditions using nested ternary operators, with a note on the importance of parentheses for clarity.
  • Several participants express concerns about the readability of code using chained ternary operators, suggesting that it may lead to confusion among colleagues.
  • There is a recurring theme that many software firms discourage or outright ban the use of complex ternary expressions in favor of clearer if statements or switch cases.
  • Some participants mention the broader implications of functional programming and its acceptance in various programming environments, referencing languages like Scala and C++ that incorporate functional features.
  • Discussion includes humorous remarks about the challenges of writing readable code and the potential backlash from peers regarding complex expressions.

Areas of Agreement / Disagreement

Participants generally agree that while nested ternary operators are technically possible, they often lead to less readable code. There is no consensus on the best approach, as opinions vary on the use of ternary operators versus traditional control structures.

Contextual Notes

Participants note that the readability of code is subjective and can depend on team standards and individual preferences. The discussion touches on the limitations of using ternary operators in professional settings, where coding standards may prohibit their use.

Who May Find This Useful

This discussion may be useful for programmers considering the use of ternary operators in C, software developers interested in coding standards, and those exploring functional programming concepts in various languages.

camel-man
Messages
76
Reaction score
0
I was wondering if anyone knew if it is possible to construct an if else if with the ternary operator in C.

I know that we can use it for if else, but what if you wanted multiple conditions for else if in your statement?

Code:
printf("%d",(a>5)?1:(a<5)?0:10);
//Just a silly example
perhaps?
 
Technology news on Phys.org
I think you can do the nested ternary ops but you can't insert arbitrary java code in there. It must be an expression.

You could use a user-defined boolean function for the condition and other functions for the result which in effect does the same thing but its probably harder to read in the long run for short if/else type work.

double y = <some-user-boolean-function>(a,b,c) ? <some-user-function-returns-a-double>(a,b,c) : <some-other-user-function-that-returns-a-double(a,b,c);
 
Last edited:
Sure. It's just another operator. So,

Code:
// Example 1, various assignments to x via conditional statements.
if (cond1)
   x = val1;
else if (cond2)
   x = val2;
else if (cond3)
   x = val3;
else
   x = val4;

// Example 2, various assignments to y via conditional statements.
if (cond1)
   if (cond2)
      if (cond3)
         y = val3;
      else
         y = val2;
   else
      y = val1;
else
   y = val4;

Writing these using the ternary operators:
Code:
// Example 1, as a single assignment statement using multiple ternary operators
x = cond1 ? val1 : cond2 ? val2 : cond3 ? val3 : val4;

// Example 2, as a single assignment statement using multiple ternary operators
y = cond1 ? cond2 ? cond3 ? val3 : val2 : val1 : val4;

You may want to use parentheses. That ternary operator evaluates right to left combined with where it lives in the C-family precedence table can lead to some surprising interpretations by the compiler.
 
Please consider that if you use such expressions in a software firm, it's likely that your colleagues will want to cut off your hands. ;)
 
I like Serena said:
Please consider that if you use such expressions in a software firm, it's likely that your colleagues will want to cut off your hands. ;)

or better yet post t online for everyone to see:

http://thedailywtf.com/
 
I like Serena said:
Please consider that if you use such expressions in a software firm, it's likely that your colleagues will want to cut off your hands. ;)
Sure. In most cases (the vast, vast majority of cases) it's better to use if statements or a case statement instead of a complex expression using ternary operators. In many software firms chaining the ternary operator is verboten. Some places simply make the ternary operator verboten, period. Some people just don't grok functional programming so they ban its appearance in any form.

There are a few cases where would I prefer the ternary operator, even chained. Clear, concise, functional. However, I can't use the ternary operator because I tend to work on projects that forbid its use. Rats! Double rats, as I am the author of the stupid coding standards on many of those projects. (I'm quite aware that quite a few people just can't grok functional programming.)
 
D H said:
Sure. In most cases (the vast, vast majority of cases) it's better to use if statements or a case statement instead of a complex expression using ternary operators. In many software firms chaining the ternary operator is verboten. Some places simply make the ternary operator verboten, period. Some people just don't grok functional programming so they ban its appearance in any form.

There are a few cases where would I prefer the ternary operator, even chained. Clear, concise, functional. However, I can't use the ternary operator because I tend to work on projects that forbid its use. Rats! Double rats, as I am the author of the stupid coding standards on many of those projects. (I'm quite aware that quite a few people just can't grok functional programming.)

If you like functional programming check out Scala, a better Java than Java. Its a combination of functional and OO programming styles.

http://www.scala-lang.org/
 
Functional programming... isn't that where you program fragments like
Code:
(setq grok (?: cond1 val1 cond2 val2 cond3 val3 val4))
just because you can?
 
Last edited:
Just be aware that it is immoral to write code that is really tough for others to read. Agree with the "cut off your hands" comments above. :-)
 
  • #10
harborsparrow said:
Just be aware that it is immoral to write code that is really tough for others to read. Agree with the "cut off your hands" comments above. :-)

and then there's APL, a true write-only language of great power, simplicity and obfuscation that upon writing your program you can never ever hope to figure out what it does in finite time but at least you have the opportunity to rewrite it if you want.
 
  • #11
jedishrfu said:
and then there's APL, a true write-only language of great power, simplicity and obfuscation that upon writing your program you can never ever hope to figure out what it does in finite time but at least you have the opportunity to rewrite it if you want.

Ah yes, for those of us that think that
Code:
(setq grok (?: cond1 val1 cond2 val2 cond3 val3 val4))
is too obvious, we can simply write something like
Code:
⍋x
to mean the same thing.
 
  • #12
I like Serena said:
Functional programming... isn't that where you program fragments like
Code:
(setq grok (?: cond1 val1 cond2 val2 cond3 val3 val4))
just because you can?
Your syntax isn't quite right, and you're using an aspect of Lisp that isn't pure. Fixing both,
Code:
(dosomethingwith (cond ((cond1) val1) ((cond2) val2) ((cond3) val3) (t val4)))

Note the lack of the setq. That's verboten in pure Lisp. Something like C's i=i+1 doesn't make sense in purely functional languages.

Functional programming requires a rather different outlook on programming.
 
  • #13
D H said:
Your syntax isn't quite right, and you're using an aspect of Lisp that isn't pure. Fixing both,
Code:
(dosomethingwith (cond ((cond1) val1) ((cond2) val2) ((cond3) val3) (t val4)))

Note the lack of the setq. That's verboten in pure Lisp. Something like C's i=i+1 doesn't make sense in purely functional languages.

Functional programming requires a rather different outlook on programming.

The best example for functional programming is in doing a generalized sorting algorithm where the comparison is left for the end programmer to provide. The comparison is placed in a function and the function is passed to the sort function and magically the data is sorted.

Scala has all kinds of examples like this using closures. A closure is a kind of function that is passed to one of many collection iterators that Scala has in its arsenal of programming constructs.
 
  • #14
C++ also has functional programming features. There's std::sort, for example. C++11 takes C++ much further along the road toward being a functional language. Lambda expressions, bindings, currying, ...
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 20 ·
Replies
20
Views
2K
Replies
1
Views
2K
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
4
Views
2K