2

for ループ条件で 3 項演算を使用することをお勧めします。三項演算でforループ条件の問題が解決される状況に遭遇したため、これを求めています。

例:

for( short i = 0 ; i < count ; i++ ){
   for( short j = 0 ; j < ( ( x[i] < y[i] ) ? x[i] : y[i] ) ; j++ ){ //Here I am using ternary operation at for loop condition place
       //.....
       //.....Some Code Here .......
       //.....
   }
}
4

5 に答える 5

6

min(x[i], y[i])より明確であるという理由だけで、私は に行きますが、コードに差し迫った問題は見られません。

于 2012-05-24T05:48:49.190 に答える
3

Personally I would go for min(x[i], y[i]). However, your readability issues can be dealt with by pre-calculating the value and using it:

for( short i = 0 ; i < count ; i++ ){
   int jCount = ( x[i] < y[i] ) ? x[i] : y[i]; // or min equivalent
   for( short j = 0 ; j < jCount ; j++ ){ 

   }
}

This changes the behaviour somewhat, in that it makes the condition blind to changes to x[i] and y[i] inside the j loop. I am not sure if that fits your use-case or not.

于 2012-05-24T06:03:47.210 に答える
2

問題はありません。

私のアドバイス。
1.shortに変更しintます。
2. #define ternary(オプション)。

#define cond(n)  (( x[n] < y[n] ) ? x[n] : y[n] )

for( int a = 0; a < count; a++)
  for( int b = 0; b < cond(a), b++)
 {

  ........code...............

 }
于 2012-05-24T08:14:05.443 に答える
2

一般的に三項演算子を使用しても問題ない場合は、for ループ条件で使用しない理由はありません。(私自身は三項演算子が好きですが、難読化されていると考える人がいることは知っています)

于 2012-05-24T05:49:18.117 に答える
1

I guess there are no issues using ternary operator , other than that it makes code not readable . But condition like this x[i] < y[i] ) ? x[i] : y[i] can sometimes create problem in case you are also modifyiong x[i] and y[i] insdide for loop . So i would suggest not to use unless you really know what you are doing

于 2012-05-24T06:04:01.267 に答える