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.
why is this bad form? Because it's unreadable?
Yes it is bad because it is unreadable.
C does not required a single or two different loops. The emitted code is an implementation defined issue.
In general, with such micro optimizations consider:
Clarity - the for (int i = (forward == true ? 0 : 10);...
choice stinks.
Maintenance.
Save your valuable time to deal with bigger issues.