0

I was recently introduced to ternary operators. I managed to make it through a year and a half of CS school without a professor ever mentioning ternary operators. This is my first quarter where my professor is using them regularly. They seem great for shortening code. So, this is a question that will help me understand the bounds of ternary operators and when/how they can be used. Is there a way to shorten the following code block using one long statements using a ternary operator?

if(age < 18){
    minors+=1;
} else if(age < 65){
    adults+=1;
}else{
    seniors+=1;
}
  • My opinion, but I find that code is much more readable when operators are surrounded by spaces, e.g. `minors += 1;`. As always, there are exceptions, e.g. that statement could be `minors++;` and the postfix and prefix operators should not be separated by space from the value they work on. – Andreas Apr 10 '16 at 22:33
  • I don't like ternary operators. Find them confusing. – BevynQ Apr 10 '16 at 22:59

3 Answers3

3

You are updating three unique variables, one way to use ternaries here is something like

minors += (age < 18) ? 1 : 0;
adults += (age >= 18 && age < 65) ? 1 : 0;
seniors += (age >= 65) ? 1 : 0;
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

You can write it as a single statement:

int dummy = (age < 18) ? (minors += 1)
          : (age < 65) ? (adults += 1)
          :              (seniors += 1);

The value of dummy is unused here. It's just a way to turn the expression into a statement.

Note that I wouldn't consider writing the logic like this in practice. There are multiple side-effects in the code, and that makes it hard to understand.

I think the intent of your current code is very clear as written. Ternary expressions have a tendency to make the code harder to read, in my experience.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • The ternary operator can be a great replacement for multiple assignment *statements*. The problem here is not the multiple statements, but the fact that they update three different *variables*. – Andreas Apr 10 '16 at 22:31
0

The ternary operator is not a good fit for your code because you are changing 3 different variables. I would leave your code as it is.

Suppose, on the other hand, that you had this

if (age < 18) {
    number += 1;
} else if (age < 65) {
    number = 8;
} else if (age < 90) {
    number += 2;
} else {
    number = 13;
}

This could be rewritten to look like a kind of switch:

number = age < 18 ? number + 1 :
         age < 65 ? 8          :
         age < 90 ? number + 2 :
                    13;

I think this is an improvement on the if version. However, it is not common to nest ternary operators in this way, so you may confuse people looking at your code if you used this version.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116