开发者

If statement in a for loop?

I would like to write something like this but I am not sure开发者_高级运维 how.

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
}


Use the ternary operator:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜