dポイントプレゼントキャンペーン実施中!

以下のようにif文の条件が
たくさん有る場合、もうすこしif文をすっきりさせる
書き方はないでしょうか?

#define AAA_1 1
#define AAA_2 2
#define AAA_3 3
#define AAA_4 4
#define AAA_5 5
#define AAA_6 6
#define AAA_7 7
#define AAA_8 8

int a;

if ( (a == AAA_1) ||
(a == AAA_2) ||
(a == AAA_3) ||
(a == AAA_4) ||
(a == AAA_7) ||
(a == AAA_8) ){
  }
if ( (a == AAA_1) ||
(a == AAA_2) ||
(a == AAA_3) ||
(a == AAA_4) ||
(a == AAA_5) ||
(a == AAA_6) ){
  }
if ( (a == AAA_1) ||
(a == AAA_3) ||
(a == AAA_4) ||
(a == AAA_5) ||
(a == AAA_8) ){
  }

A 回答 (7件)

配列をひとつ間において



int check_1[] = {AAA_1, AAA_2, AAA_3, AAA_4, AAA_7, AAA_8, -1};
int check_2[] = {AAA_1, AAA_2, AAA_3, AAA_4, AAA_5, AAA_6, -1);
int check_3[] = {AAA_1, AAA_2, AAA_3, AAA_4, AAA_5, AAA_8, -1);

Cの関数でこんなのを作って、
(src と、その後の、int のリスト(負の数で、リストの終端)を比較して、一致する物があれば、true を返す)

bool in(int src, int terget[])
{
for (int i = 0; terget[i] >= 0; i++)
{
if(src == terget[i] return true;
}
return fasle;
}

if(in(a, check_1)
{ }

if(in(a, check_2)
{ }

if(in(a, check_3)
{ }

Cの関数で、こんなのを作って、
(上と同じ関数の、可変引数関数版)

#include <stdarg.h>

bool in(int src, ...)
{
va_list args;
va_start(args, src);
while(1)
{
int terget = va_arg(args, int);
if(terget < 0)
{
va_end(args);
return false;
}

if (terget == src)
{
va_end(args);
return true;
}

}
}

if(in(a, AAA_1, AAA_2, AAA_3, AAA_4, AAA_7, AAA_8, -1)
{ }

if(in(a, AAA_1, AAA_2, AAA_3, AAA_4, AAA_5, AAA_6, -1)
{ }

if(in(a, AAA_1, AAA_2, AAA_3, AAA_4, AAA_5, AAA_8, -1)
{ }

最新のC++だったら、もう少し簡単にできた気がする。
    • good
    • 0

個人的にはNo2さんの回答が一番好みです。


専用の関数や宣言を増やしたくない場合、私は以下のように書いたりしています。
switch (a) {
case AAA_1:
case AAA_2:
case AAA_3:
case AAA_4:
case AAA_7:
case AAA_8:
//処理
break;
}
switch (a) {
case AAA_1:
case AAA_2:
case AAA_3:
case AAA_4:
case AAA_5:
case AAA_6:
//処理
break;
}
switch (a) {
case AAA_1:
case AAA_3:
case AAA_4:
case AAA_5:
case AAA_8:
//処理
break;
}
    • good
    • 0

まずやるべきは、条件を整理できないか検討する事じゃないかと思います。

    • good
    • 0

#define AAA_1 1


#define AAA_8 8
#define chk(A,B) (((A)<=AAA_8)&&((B)[((A)-(AAA_1))]=='1'))
if(chk(a,"11110011")){
}
if(chk(a,"11111100")){
}
if(chk(a,"11111001")){
}
    • good
    • 0

#3さんが触れられてる switch文を使う、っというのもよさそうにおもいます。


でもって、処理の内容によるけど、三つのifをまとめて、(最初のifの中の処理を1、二番目のを2、三番目のを3っとすると)
aがAAA_1なら1,2,3を、AAA_2なら1,2、を、と言う具合に、分岐数を増やすほうが見通しがよくなるかもしれません。
    • good
    • 0

case文、switch文、 if(...){...} else if(...){...} .... 構文等を使って下さい。



複数の同一の変数に対する連続したif文の内、一つだけしかifの条件が満足しない場合に、質問の書き方では条件を満たした後のif文は無駄ですし、プログラムも読み難くなります。

C OR C++ 条件分岐文 OR 制御文
C OR C++ case文 "else if"文 switch文
  等とサーチして調べて下さい。
  ==> 
http://masudahp.web.fc2.com/cl/kiso/ck0205.html
    • good
    • 0

int a;


int b ;
b = 1 << (a - 1) ;

if (b & 0xcf) {
  }
if (b & 0x3f) {
  }
if (b & 0x9d){
  }
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!