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;
}
You are updating three unique variables, one way to use ternaries here is something like
You can write it as a single statement:
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.
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
This could be rewritten to look like a kind of
switch
: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.