-2

Testing some snippets, I found a very strange behaviour. I have 2 local variables that it's not initialized. And one that it's used later in the program is always initialized to zero, the other has a garbage value (what I expected to get as a normal behavior). As if the compiler checks that I will use it in a while loop and it initialized to zero implicitly. I don't understand this behavior.

int i,j; // variable declaration and initialization 
cout << i <<' '<< j << endl;
while ( i < 10 ) // condition 
   { cout << i << '\n'; 
     i++; // variable update 
   }

If I include the above snippet in a main program, it seems it works well always. The value of i is always zero before it enters the while loop and the while loop works well always. But the variable j has any unknown variable (garbage)

In fact,I copied this snippet directly from the book: Jumping into C++ by Alex Allain, page # 74. (I added variable j for comparison only)

froycard
  • 365
  • 2
  • 4
  • 10
  • Cannot reproduce (probably because it isn't reproducible, as others already said). For yourself, try to boil down your snippet to [example] - not a "snippet to include", but something that is a whole, self-consistent compilable thing. (e.g. I needed to provide `main`, include `iostream` and use `std` in order to compile your code, which means it's already probably different than yours.) Then you can use `-S` switch to see the assembly and see for yourself what is happening. (For C++ you're likely to get over a thousand lines, so keeping it C-only would let you see a clearer picture.) – Amadan Aug 13 '19 at 04:22
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Aug 13 '19 at 05:16
  • You can't tell a zero that comes from an initialisation from a zero that just happens to be there. Zero is no less "garbage" than any other number. – molbdnilo Aug 13 '19 at 08:00

1 Answers1

2

Line 1 of the program is a declaration, not an initialization. Using uninitialized variables leads to undefined behavior. It’s pure luck that the loop variable i is initialized to 0 if it indeed is 0.

ManLaw
  • 115
  • 1
  • 10