Instead of having two different loops that have identical printf statements, you can make a for loop that uses a boolean and ternaries to switch it forward or backward.
Why is this bad form? Because it's unreadable? Does the compiler make two different loops, anyways?
Just curious as to what this means for the compiled result.
Example:
for (int i = (forward == true ? 0 : 10);
(forward == true ? i <= 10 : i >= 0);
(forward == true ? ++i : --i))
printf(" %d", i);
Instead of:
// Forward
for (int i = 0; i <= 10; ++i)
printf(" %d", i);
// Backward
for (int i = 10; i >= 0; --i)
printf(" %d", i);
I was given this interesting suggestion:
for (int i = 0; i < 10; i++) {
printf(" %d", (forward ? i : 9-i));
}
After checking the assembly code using Godbolt, it is possible that the compiler will make one (complicated) or two (simplified) loops.
forward == trueis poor code. Better asforward.forwardso it switches to backwards when it reaches 10. Or is the second snippet supposed to be two alternative loops, not one after the other?forward.