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
You cannot use break;
this way, it must appear inside the body of the for
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 from main()
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()
and longjmp()
, 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 a jmpbuf
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 by foo()
: longjmp()
will jump from its location, deep inside the internals of foo()
, possibly many levels down the call stack, to the setjmp()
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 iterate 101
times because you use the <=
operator. The idiomatic for
loop uses for (int i = 0; i < 100; i++)
to iterate exactly the number of times that appears as the upper (excluded) bound.