-2

I was trying learn behaviour of POD in case of goto. Following is the program I used:

#include <iostream>
void f(int i){
    if (i < 10)
         goto jump1;
    int j;
    jump1:
         std::cout << j;
}

int main()
{
    f(9);
}

Why is j initialised with 0?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Sumit Gera
  • 1,249
  • 4
  • 18
  • 34

2 Answers2

1

There is nothing to initialize a local non-static variable to zero in the standard, it's just a custom/random behaviour of you compiler.Reading a value from uninitialized variable can invoke an undefined behaviour. The goto has nothing to do with that declaration.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • I was expecting a garbage value in j. And this undefined behaviour of my compiler cost me 3 downvotes. – Sumit Gera Jan 25 '15 at 11:28
  • For me that zero which comes from an uninitialized variable is garbage! – masoud Jan 25 '15 at 11:29
  • Undefined behavior can mean the value is garbage, the value is 0 or the compiler can simply remove all operations depending on that variable, or can make demons fly out of your nose. – bolov Jan 25 '15 at 11:29
1

The goto jump itself is fine. By [stmt.dcl]/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 [...] and is declared without an initializer (8.5).

However, what is not legal is to read an uninitialized variable by [dcl.init], and thus your program has undefined behaviour at runtime if you call f with an argument less than 10.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084