I'm currently trying to figure out a way to break out of a for
loop from within a function called in that loop. I'm aware of the possibility to just have the function return a value and then check against a particular value and then break, but I'd like to do it from within the function directly.
This is because I'm using an in-house library for a specific piece of hardware that mandates the function signature of my function to look like this:
void foo (int passV, int aVal, long bVal)
I'm aware that not using a return value is very bad practice, but alas circumstances force me to, so please bear with me.
Consider following example:
#include <stdio.h>
void foo (int a) {
printf("a: %d", a);
break;
}
int main(void) {
for (int i = 0; i <= 100; i++) {
foo(i);
}
return 0;
}
Now this does not compile. Instead, I get a compilation error as follows:
prog.c: In function 'foo': prog.c:6:2: error: break statement not within loop or switch break;
I know what this means (the compiler says that the break in foo()
is not within a for
loop)
Now, what I could find from the standard regarding the break statement is this:
The break statement causes control to pass to the statement following the innermost enclosing while, do, for, or switch statement. The syntax is simply break;
Considering my function is called from within a for
loop, why doesn't the break statement break out of said for loop? Furthermore, is it possible to realise something like this without having the function return first?
If you cannot use the
break
instruction you could define a local variable in your module and add a second run condition to thefor
loop. For example like the following code:Note that in this example this is not exactly a
break
-instruction, but thefor
loop will not do another iteration. If you want to do abreak
you have to insert anif
-condition with the variablecontinueLoop
which leads tobreak
:You cannot use
break;
this way, it must appear inside the body of thefor
loop.There are several ways to do this, but neither is recommended:
you can exit the program with the
exit()
function. Since the loop is run frommain()
and you do not do anything after it, it is possible to achieve what you want this way, but it as a special case.You can set a global variable in the function and test that in the
for
loop after the function call. Using global variables is generally not recommended practice.you can use
setjmp()
andlongjmp()
, but it is like trying to squash a fly with a hammer, you may break other things and miss the fly altogether. I would not recommend this approach. Furthermore, it requires ajmpbuf
that you will have to pass to the function or access as a global variable.An acceptable alternative is to pass the address of a
status
variable as an extra argument: the function can set it to indicate the need to break from the loop.But by far the best approach in C is returning a value to test for continuation, it is the most readable.
From your explanations, you don't have the source code for
foo()
but can detect some conditions in a function that you can modify called directly or indirectly byfoo()
:longjmp()
will jump from its location, deep inside the internals offoo()
, possibly many levels down the call stack, to thesetjmp()
location, bypassing regular function exit code for all intermediary calls. If that's precisely what you need to do to avoid a crash,setjmp()
/longjmp()
is a solution, but it may cause other problems such as resource leakage, missing initialization, inconsistent state and other sources of undefined behavior.Note that your
for
loop will iterate101
times because you use the<=
operator. The idiomaticfor
loop usesfor (int i = 0; i < 100; i++)
to iterate exactly the number of times that appears as the upper (excluded) bound.break
is statement which is resolved during compile time. Therefore the compiler must find appropriate for/while loop within the same function. Note that there is no guarantee that the function couldn't be called from somewhere else.If you cannot handle return values, can you at least add a Parameter to the function: I can imagine a solution like that:
It's my first post, so, please forgive me, if my formatting is messed up :)
You can throw an error in your function inside the loop and catch that error outside the loop.
This question has already been answered, but I think it is worth delving into all of the possible options to exit a loop in c++. There are basically five possibilities:
break
conditionreturn
conditiongoto
In the following, I will describe use cases for these options using c++14. However, you can do all of these in earlier versions of c++ (except maybe exceptions). To keep it short, I will omit the includes and the main function. Please comment, if you think some part needs more clarity.
1. Using a loop condition
The standard way to exit a loop is a loop condition. The loop condition is written in the middle part of a
for
statement, or between the parentheses of awhile
statement:The loop condition decides if the loop should be entered, and if the loop should be repeated. In all of the above cases, the condition has to be
true
, for the loop to be repeated.As an example, if we want to output the number from 0 to 2, we could write the code using a loop and a loop condition:
Here the condition is
i <= 2
. As long as this condition evaluates totrue
, the loop keeps running.An alternative implementation would be to put the condition into a variable instead:
Checking the output for both versions, we get the desired result:
How would you use a loop condition in an real world application?
Both versions are widely used inside c++ projects. It is important to note, that the first version is more compact and therefore easier to understand. But the second version is usually used if the condition is more complex or needs several steps to be evaluated.
For example:
2. Using a
break
conditionAnother simple way to exit a loop, is to use the
break
keyword. If it is used inside the loop, the execution will stop, and continue after the loop body:This will output the current number, and increment it by one, until
i
reaches a value of 3. Here theif
statement is ourbreak
condition. If the condition istrue
, the loop is broken (note the!
) and the execution continues with the next line, printingdone
.Doing the test, we indeed get the expected result:
It is important, that this will only stop the innermost loop in the code. Therefore, if you use multiple loops, it can lead to undesired behaviour:
With this code we wanted to get the same result as in the example above, but instead we get an infinite loop, because the
break
only stops the loop overi
, and not the one overj
!Doing the test:
How would you use a
break
condition in an real world application?Usually
break
is only used to skip parts of an inner loop, or to add an additional loop exit.For example, in a function testing for prime numbers, you would use it to skip the rest of the execution, as soon as you found a case where the current number is not prime:
Or, if you are searching a vector of strings, you usually put the maximum size of the data in the loop head, and use an additional condition to exit the loop if you actually found the data you are searching for.
3. Using a
return
conditionThe
return
keyword exits the current scope and returns to the calling function. Thus it can be used to exit loops, and in addition, give back a number to the caller. A common case is to usereturn
to exit a loop (and its function) and return a result.For example, we can rewrite the
is_prime
function from above:The
return
keyword can also be used to exit multiple loops:How would you use a
return
condition in an real world application?Inside smaller functions,
return
is often used to exit loops and directly return results. Furthermore, inside larger functions,return
helps to keep the code clear and readable:Which is much easier to understand, than:
4. Using exceptions
Exceptions are a way to mark exceptional events in your code. For example, if you want to read data from a file, but for some reason the file doesn't exist! Exceptions can be used to exit loops, however the compiler usually generates a lot of boilerplate code to safely continue the program if the exception is handled. Therefore exceptions shouldn't be used to return values, because it is very inefficient.
How would you use an exception in an real world application?
Exceptions are used to handle truly exceptional cases. For example, if we want to calculate the inverse of our data, it might happen that we try to divide by zero. However this is not helpful in our calculation, therefore we write:
We can the handle this exception inside the calling function:
If
data
contains zero, theninverse_data
will throw an exception, thebreak
is never executed, and the user has to input data again.There are even more advance options for this kind of error handling, with additional error types, ..., but this is a topic for another day.
** What you should never do! **
As mentioned before, exceptions can produce a significant runtime overhead. Therefore, they should only be used in truly exceptional cases. Although it is possible to write the following function, please don't!
5. Using
goto
The
goto
keyword is hated by most programmers, because it makes code harder to read, and it can have unintended side effects. However, it can be used to exit (multiple) loops:This loop will end (not like the loop in part 2), and output:
How would you use a
goto
in an real world application?In 99.9% of the cases there is no need to use the
goto
keyword. The only exceptions are embedded systems, like an Arduino, or very high performance code. If you are working with one of these two, you might want to usegoto
to produce faster or more efficient code. However, for the everyday programmer, the downsides are much bigger than the gains of usinggoto
.Even if you think your case is one of the 0.1%, you need to check if the
goto
actually improves your execution. More often than not, using abreak
orreturn
condition is faster, because the compiler has a harder time understanding code containinggoto
.