When I'm reading the C++ standard, it seems that the following code is perfectly fine according to the standard.
int main() {
goto lol;
{
int x;
lol:
cout << x << endl;
}
}
// OK
[n3290: 6.7/3]: 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 variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer.
Why should it work? Isn't it still dangerous to jump over its definition and use undefined x
? And why should the existence of an initializer make any difference?
You'd use an uninitialized x
anyways, since int x;
is as uninitialized as it's going to get. The existence of an initializer makes of course a difference, because you'd be skipping it. int x = 5;
for example initializes x
, so it would make a difference if you jumped over it or not.
Isn't it still dangerous to jump over its definition and use uninitialized
x
?
But x
would be uninitialized anyway, because it was declared without an initializer! So the goto
might be skipping over assignment statements that set (sort-of-initialize) x
, but it's not surprising that goto
can skip over assignment statements; and the declaration itself doesn't actually do anything unless there's 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