Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you transfer control to a if(false) block by using goto?

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?

like image 705
Be Ku Avatar asked Jul 05 '21 14:07

Be Ku


People also ask

Why should we avoid goto statement in C?

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.

When should you use GOTO in C?

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.


Video Answer


1 Answers

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.

like image 197
cigien Avatar answered Nov 10 '22 14:11

cigien