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)?
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.
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