简体   繁体   English

如果在for循环中声明?

[英]If statement in a for loop?

我想写这样的东西,但我不确定如何写。

for(int i = 0; i < ( the greater value between intA and intB ); i++)

The expression in the middle of your for statement works exactly like any if statement; for语句中间的表达式与if语句完全一样。 the loop only continues when the expression evaluates as true. 仅当表达式的值为真时,循环才会继续。 So there are a few logically equivalent ways to write what you want: 因此,有几种逻辑上等效的方式可以编写所需内容:

// using a ternary operator
for (int i=0; i < ((intA > intB) ? intA : intB); ++i)
{
    // do stuff
}

// using a simple Boolean OR
for (int i=0; i < intA || i < intB; ++i)
{
    // do stuff
}

// using a MAX macro
for (int i=0; i < MAX(intA, intB); ++i)
{
    // do stuff
}

But in your specific case, none of these are ideal since the first two aren't really clear code and they all evaluate intA vs intB on each iteration through the loop. 但是在您的特定情况下,这些都不是理想的,因为前两个不是真正清晰的代码,并且它们在循环中每次迭代时都评估intAintB What's even better is something like: 更好的是:

int maxAB = MAX(intA, intB);
for (int i=0; i < maxAB; ++i)
{
   // do stuff
}

使用三元运算符:

for(int i = 0; i < (intA > intB ? intA : intB); i++)

Use tha MAX macro. 使用tha MAX宏。

MAX( a, b )

If it's not available, you can define it: 如果不可用,则可以定义它:

#define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
for(int i = 0; i < ((a) < (b) ? (a) : (b)); i++)

I would suggest using the MAX macro or using an extra if statement before each execution of the for statement. 我建议在每次执行for语句之前使用MAX宏或使用额外的if语句。 Using the ternary operator is not clear enough to support future mainteinance. 使用三元运算符还不够清晰,无法支持将来的维护。 But that's just my opinion. 但那只是我的个人意见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM