问题
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)?
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.
回答1:
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++ Standart 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.
回答2:
The reason for the rule is that jumping over an initialization leaves the object in an undefined state. When you get to the end of the function, destroying those uninitialized objects might not work.
One exception is obviously that
int i;
leaves the int
uninitialized anyway, so skipping that is just half bad.
If you want to leave a function early, a quick return
is an option to avoid the goto
.
来源:https://stackoverflow.com/questions/11306799/why-does-c-enforce-such-behavior-in-crosses-initialization