简体   繁体   中英

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

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. Using the ternary operator is not clear enough to support future mainteinance. But that's just my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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