English 中文(简体)
在“为”环状状态中使用“永久操作”是一种良好做法吗?
原标题:Is it a good practice to use "ternary operation" in the "for" loop condition?

Is it a good practice to use ternary operation in for loop condition. I am asking this because i have come across the situation where in ternary operation will resolve my issue in for loop condition.

对于 例如 :

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 .......
       //.....
   }
}
最佳回答

我看不出有什么问题

My advice.
1. short change to int.
2. #define ternary(optional).

#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...............

 }
问题回答

我选 min(x(i),y(i) ,只是因为它更清楚,但我看不出你的代码有什么问题。

我个人会选择 min(x(i),y(i) 。然而,您的可读性问题可以通过预先计算和使用数值来解决:

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++ ){ 

   }
}

这在某种程度上改变了行为, 因为它使状态无法对 x[i] y[i] y[i] j 环中的变化进行修正。 我不知道这是否适合您的使用大小写 。

如果你同意使用长期操作员 一般来说, 那么没有理由不使用它 在你的循环状态。 (我喜欢 永久操作员自己, 但我知道有些人认为它 混淆了)

我想,除了它使代码无法读取之外,使用长期运算符没有问题。 但像这样的条件 x(i) < y[i]? x(i) : y[i] 有时会造成问题, 以防您同时修改 x(i) 和 y[i] , 无法用于循环。 所以我建议您不使用, 除非您真正知道自己在做什么 。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签