4

Back in college I've been told that using break; and continue; outside switch statements (e.g. to escape for or while loops) is wrong, bad practice and bad habits at the same time because it only means that you cannot write loops properly. Is it really?

A friend of mine also told me that using conditional ?: is bad practice too, however I've started using this more often because it allows me to write stuff in less than 70 lines of code while without it i'd end up with something like 200 lines of code. It comes in very useful in almost every project I work on and I use it quite often. Should I stop?

p.s.w.g
  • 4,135
  • 4
  • 28
  • 40
user84585
  • 41
  • 1
  • 2
  • 2
    `break` and `continue` are fine when used in moderation. `?:` is a matter of style. I dislike it, but it's not necessarily bad. – CodesInChaos Mar 16 '13 at 19:24
  • 5
    This should be split into two questions. – whatsisname Mar 16 '13 at 20:05
  • Surprises are bad. If you check conditions at the beginning of a method and return, and the structure is clear and expected, it's fine. If you bury a return in the middle of a nested logic loop it will surprise someone someday, which is bad. I had my first boss tell me that ?: was "Bad" because nobody ever used or understood it and therefore it would take extra time to understand the code. If he was right about the assumption, then his conclusion was also correct. I hope he wasn't. – Bill K Sep 24 '14 at 19:10
  • Many years ago a conversation with my boss. He says "A page of my code is more readable than one page of your code". I answer: "True, but one page of my code does more than 4 pages of your code". – gnasher729 Jun 25 '19 at 19:12

4 Answers4

13

On break and continue

I don't think there's anything fundamentally wrong with a break or continue. I think the motivation to avoid them is really has to do more with readability than anything else. Consider the following loops (not strictly c/c++ code):

// loop 1
for(int i = 0; i < a.length; i++)
{
    if (!found(a[i]))
        continue;

    result = a[i];
    break;
}

// loop 2
for(int i = 0; i < a.length; i++)
{
    if (found(a[i]))
    {
        result = a[i];
        break;
    }
}

// loop 3
{
    bool resultFound = false;
    for(int i = 0; !resultFound && i < a.length; i++)
    {
        if (found(a[i]))
        {
            result = a[i];
            resultFound = true;
        }
    }
}

All three of these loops run essentially the same code, but are written in slightly different ways. The real question is which one most effective conveys the author's intent?

  • loop 1 - very bad. The logic here seems to be inverted, and the continue is pretty much gratuitous. If translated to English this would read something like:

    Loop through the list while the item is not found, but if it is set the result then stop.

  • loop 2 - good. This is how such loops are generally written. If translated to English this would read something like:

    Loop through the list and if the item is found, set the result then stop.

  • loop 3 - slightly bad. The break / continue logic is found in the condition of the for loop, which is not as common. It means if someone reading your code wants to know what will happen next, they have to go back to the top of the loop. A break (as in loop 2) specifies that logic in exactly one place. If translated to English this would read something like:

    Loop through the list while the item is not found and if an item is found, set the result.

On the ?: operator

Again, there's nothing fundamentally wrong with it. It's really a matter of personal style and readability.

// Good uses of conditional operator
string result = (someBool) ? "YES" : "NO";
string oddness = (someInt % 2 == 0) ? "even" : "odd";

// Bad use of conditional operator
int result = ConditionA() ? (ConditionB() ? 0 : 1) : (ConditionC() ? 2 : 3);

Again the programmers intent is pretty clear in the first two examples, but is much more obscured in the last.

Deduplicator
  • 8,591
  • 5
  • 31
  • 50
p.s.w.g
  • 4,135
  • 4
  • 28
  • 40
  • 2
    +1: your bad use of conditional operator is still more readable than what I saw in the field. – scrwtp Mar 16 '13 at 23:44
  • As for break/continue, I remember debugging through a loop with a lengthy body, that had a single continue thrown in, nested somewhere deep in the middle. Good times. – scrwtp Mar 16 '13 at 23:50
  • Loop1 avoids one level of nesting, resulting -on non-optimizing compiler- in less "jump" instruction once the code is translated. May be not "beautiful", but that 's how many STL implementation are written. If performance is important, solve the most frequent case first, with shortest jump is what makes the processor less "heated". – Emilio Garavaglia Jan 12 '14 at 08:04
  • 1
    The "bad use of conditional operator" wouldn't be bad if it was properly indented... also, the extra parentheses are interesting. – Deduplicator Jun 13 '17 at 21:02
  • Your presumption that a lack of "Readability" cannot make something "Fundamentally wrong" is amusing. Once your code compiles and runs, in fact, readability is arguably the only thing that can make your code Fundamentally wrong. – Bill K Feb 27 '18 at 20:29
  • I guess extremely inefficient code is also wrong--but not so fundamentally wrong as unreadable code. If it's readable/understandable I can fix anything else. – Bill K Feb 27 '18 at 20:42
  • 1
    Note that version 3 leaves the index i one larger than you expect - good reason for a bug. – gnasher729 Jun 25 '19 at 19:13
12

break and continue are perfectly fine, there are many programs that will be hard to express without them. The only time using them become a problem is if you want to formally prove correctness. In most real life code, correctness are ensured using unit test, not formal proof. Nevertheless, if a loop can be just as easily expressed without break and continue, don't use them unnecessarily.

Using ?: is actually a good practice. Good practice for ?: though, is that all expressions (i.e. conditional part, true part, and false part) should have no side effect except for their return value. If the expression contains side effect, you might want to use conventional if-block statement instead. This is a case of command-query separation, command that have side effect should use if-block while queries that are side-effect-free should use :?, this is a guideline though, not a hard and fast rule, sometimes complicated queries might be better expressed using if-block.

Lie Ryan
  • 12,291
  • 1
  • 30
  • 41
4

break and continue are invaluable, they often make the code shorter and better readable.

Well, except when they don't. If you find yourself using them too often or multiple times in one block, it may be that you really want the loop body to be a function (i.e. "method" in the OO terminology). It's sometimes better to have a function with early returns than a block with multiple breaks and continues.

Regarding ?:, this is actually the functional cousin of the if statement. Functional programming is hip, so yes, use it. But remember, that functional code should be free of side effects, like others here said.

Ingo
  • 3,903
  • 18
  • 23
1

It is just a tool of programmers. No tool is bad or good by itself, it is on the user how efficiently he/she can use that tool and what he can produce with that.

It becomes necessary when you want to write optimized codes and when there is no sense to keep going further into the loops

Very common example to use break statement is into the Bubble sort algorithm. When make a check that if no swap is done into the loop stop further looping as the array is already sorted out.

Same time it is bad when it is used badly into nested loops and you embed into too much nested loops that you forgot the flow and highly chances are that you can get logical errors into your code.

? : ---is a way to write code. Just a short hand, also is a tool and depends where you use it. Can reduce lines of code on some places and on the same time can reduce the code readability.

Abdul Rehman
  • 111
  • 4