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)
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.
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++) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With