1

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++)
4
  • It's weird that that's how you guys read his question, for me the if outside the for expression makes me think he wants to test the resulting values or something. Commented Sep 16, 2011 at 19:33
  • I think you mean for not if at the start there. Commented Sep 16, 2011 at 19:33
  • @Blindy The title says it all... Commented Sep 16, 2011 at 19:33
  • more like an IQ question rather than a programming related query..!! Commented Sep 16, 2011 at 19:47

5 Answers 5

5

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 good answer. The key point is that the for loop conditional is evaluated on each iteration, so when possible avoid unnecessary evaluations like adpalumbo did with his maxAB variable in the last code block example.
2

Use the ternary operator:

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

Comments

1

Use tha MAX macro.

MAX( a, b )

If it's not available, you can define it:

#define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )

4 Comments

Are all those parenthesis needed?
huh? I said parenthesis, not parameters.
Ooops... sorry : P The parenthesis are needed in case you are dealing with complex expressions, instead of variables.
Ooooh... assignment operators and the comma operator have lower precedence than the ternary operator. Eck.
0
for(int i = 0; i < ((a) < (b) ? (a) : (b)); i++)

1 Comment

Either your conditional or your operands are backwards. Right now if a is smaller then the value of the ternary operator is a
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.