Hello. It is a trip to the vocational school world (self-proclaimed).
Recently, the reputation of the ternary operator is not good around me (?), So I would like to take this opportunity to tell you about the wonderfulness of the ternary operator.
As the name implies, a ternary operator is an operator consisting of three terms (expressions).
I have no body or lid, so I will explain it in more depth.
First, the ternary operator has the following format.
<Conditional expression> ? <Conditional expressionがtrueの場合の式> : <Conditional expressionがfalseの場合の式>
There may be symbols that you are not familiar with when writing programs here.
Yes, it's the "?
" Mark.
This is called the ** conditional operator **, and it has the role of branching the process to the two items that follow "?
" Depending on the conditional expression.
This makes it possible to dramatically refresh the processing described in the if statement.
For example, suppose there is a scene where you want to switch the bool (Boolean) type variable flag
alternately between true and false as follows.
if(flag)
{//If flag is true, set to false
flag = false;
}
else
{//If flag is true, set to false
flag = true;
}
It seems that it was long. However, if this is described using the ternary operator, it becomes like this.
flag ? false : true;
The processing that seemed to be so long is so refreshing! There was such a wonderful thing! It must be fine tomorrow!
I would like to say that, but it is not always so easy. Please see the following code.
int num = flag ? flag2 ? flag4 ? 1 : 2 : flag5 ? 3 : 4 : flag3 ? flag6 ? 5 : 6 : flag7 ? 7 : 8;
How is it? Even with the convenient ternary operator, if you use it incorrectly, the readability will drop to the ground.
There is absolutely no such thing in the world. It's the same in programming. If you make a mistake in using useful tools, you will be back in the Stone Age. And it is none other than you reading this article who thinks about how to use the tool.
Think about where to use it and have a good development life.
Recommended Posts