I've thought of following code by trying to solve a difficult 'nested-condition' problem:
goto error;
if (false)
{
error:
cout << "error block" << endl;
}
else
{
cout << "else block" << endl;
}
When I run this code, only error block
is displayed, as expected (I guess?). But is this defined behavior across all compilers?
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.
Yes, this is well defined. From stmt.goto#1
The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label located in the current function.
There are some restrictions, e.g. a case label cannot cross a non-trivial initialization
goto error;
int i = 42;
error: // error: crosses initialization of i
But these don't apply to your example. Also, in the case of crossing an initialization, this is a hard compiler error, so you don't have to worry about undefined behavior.
Note that once you jump to the case label error
, you're effectively inside the true branch of the if
condition, and it doesn't matter that you got there via a goto
. So you're guaranteed that the else
branch will not be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With