Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto crosses initialization [duplicate]

Tags:

c++

Let's say I have some c++ code:

if (error)
    goto exit;
... 
// size_t i = 0; //error
size_t i;
i = 0;
...
exit:
    ...

I understand we should not use goto, but still why does

size_t i;
i = 0;

compile whereas size_t i = 0; doesn't?

Why is such behavior enforced by the standard (mentioned by @SingerOfTheFall)?

like image 632
Akshit Khurana Avatar asked Jul 03 '12 08:07

Akshit Khurana


1 Answers

You can't jump over initialization of an object.

size_t i = 0; 

is an initialization, while

size_t i;
i = 0;

is not.

The C++ Standard says:

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer.

like image 139
SingerOfTheFall Avatar answered Nov 02 '22 09:11

SingerOfTheFall