2

I want to put if statements within my for loop checking parameters but I don't know how to do it, I want this so I don't have to duplicate my code and make it huge, redundant and messy.

This is what I am trying to do

for( int i = elevator1CurrentStatus.floorNumber; if(boundary == 9) i<boundary else i>boundary ;i+=i+countDirection){

//Code Here 

}

How would I implement this? Basically I want the test statement stating whether to count up or down to depend on a variable and select which direction based on that variable. Count direction is implemented earlier and is either +1 or -1. for( int i = elevator1CurrentStatus.floorNumber; (if(boundary == 9) iboundary;) ;i+=i+countDirection)

 for( int i = elevator1CurrentStatus.floorNumber; (if(boundary == 9) i<boundary else i>boundary) ;i+=i+countDirection)
1
  • Can you explain your IF clause? What are you trying to do in if(boundary == 9) i<boundary else i>boundary Commented Nov 10, 2013 at 2:49

2 Answers 2

8

Use ternary operator:

for(int i = elevator1CurrentStatus.floorNumber; 
    boundary == 9 ? i < boundary : i > boundary; 
    i += i + countDirection) {

//Code Here 

}

But I would move the condition to separate function/method to improve readability.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I am looking for, thanks! I'll accept this as the answer when it lets me
YOu might want to add a few brackets here and there - to improve readability. (boundary == 9) ? (i < boundary): (i > boundary);, for example.
2

I will suggest to put the condition in a separate function. It will make it more readable. Try not to inline complex conditions. Also, you can now use any multi-level if-else, switch case or any other operation that returns a boolean.

Here is what you can do:

bool conditionCheck(int i, int boundary) {
        if (boundary == 9) {
            return i < boundary;
        } else {
            return i > boundary;
        }
    }

int main(int argc, char *argv[]) {
        int boundary = 10;
        int i = 0;
        for (i = 0; conditionCheck(i, boundary); i++) {

        }

    }

4 Comments

Invalid syntax. The question is about C++. YOur code is not C++.
@SigTerm Is it ok now :D
Nope. Still not C++. Grab a C++ compiler, try to compile it, see what happens.
@SigTerm Thanks. I was just doing that and by the time I came back it was already corrected. I am going to kill myself of shame now :(

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.