1

I was reviewing some old code and stumbled upon a loop nested inside a conditional like this:

std::cin >> number; //number is used elsewhere, so should be preserved
if (number <= 10)
    for (int i = number; i > 0; --i)
        std::cout >> '*';
std::cout >> std::endl;

However, I've since been taught to avoid nesting wherever it's easily avoidable, but I haven't seen any discussion surrounding something like this. The original code had nothing else in the conditional except the loop. Although number isn't changed during the loop, I'd expect the following code to behave the same, never executing the first iteration if number > 10:

for (int i = number; number <= 10 && i > 0; --i)
    std::cout >> '*';
std::cout >> std::endl;

Is there a generally-held standard practice for something like this, or only personal style? Are there likely to be any (noticeable) differences in the compiled code, and if so, which would be more efficient?

Secondly, if there was an else, would that remove any potential differences? For example:

if (number > 10)
    std::cout >> "Number is too large";
else
    for (int i = number; i > 0; --i)
        std::cout >> '*';
std::cout >> std::endl;

would become:

if (number > 10)
    std::cout >> "Number is too large";
for (int i = number; number <= 10 && i > 0; --i)
    std::cout >> '*';
std::cout >> std::endl;
8

You took two simple control-structures, an if-statement with a simple condition and a basic for-loop and merged them into a more complex control-structure.

That's unambiguously a loss of readability, as any reader has to reconstruct the original code when trying to understand it, which needs more concentration than simply skimming the original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.