LoginSignup
1
0

More than 3 years have passed since last update.

条件演算子・3項演算子

Last updated at Posted at 2020-07-18

3項演算子の記述方法

if・elseの場合
条件判定式 ? trueの場合 : falseの場合

if・else if・elseの場合
条件判定式1 ? trueの場合 : 条件判定式2 ? trueの場合 : falseの場合

ちなみに、条件判定後の処理に関してですが
セミコロン(;)は行の最後以外には記述してはいけません。

if・elseの場合

int x = 0;

//if・elseで記述した場合
if(x <= 0){
   printf("true");
}
else{
   printf("false");
}

//3項演算子で記述した場合
x <= 0 ? printf("true") : printf("false");

//結果

true
true

if・else if・elseの場合

int x = 0;

//if・elseで記述した場合
if(x < 0){
   printf("if");
}
else if(x >= 0){
   printf("else if");
}
else{
   printf("else");
}

//3項演算子で記述した場合
x < 0 ? printf("if") : x >= 0 ? printf("else if") : printf("else");

//結果

else if
else if

最後に

3項演算子はそんなに多用することはないですが、覚えておくに越したことはないです。
良ければ、使ってみてください!

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0