Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it OK to jump into the scope of an object of scalar type w/o an initializer?

Tags:

c++

goto

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?

like image 727
Eric Z Avatar asked Dec 16 '11 03:12

Eric Z


2 Answers

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.

like image 188
Xeo Avatar answered Nov 01 '22 01:11

Xeo


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.

like image 35
ruakh Avatar answered Nov 01 '22 01:11

ruakh