-5

Consider the code snippet:

int main()  
{
int n;
cout<<n;
float f;
cout.setf(ios_base::fixed,ios_base::floatfield);
cout<<endl<<f;
char ch;
cout<<endl<<static_cast<int>(ch);
return 0;
}

Output:

0
0.000000
0

Why it is not set to the garbage value instead of zero? Is it the consequence of undefined behavior? Compiled with g++4.8.2 on Ubuntu 14.04.

dlpsankhla
  • 132
  • 1
  • 2
  • 9

2 Answers2

3

This is a compiler- and option-specific effect.

Static variables are zero-initialized first of all. Automatic local variables have no such guaranteed initialization. But a compiler can add zero-initialization, just to be “helpful”.

You're accidentally right that for the presented code the 0 result is “the consequence of undefined behavior”. But that's only because using an indeterminate value of type int is undefined behavior, or at least was UB up till and including C++11. It's a bit unclear whether accessing an indeterminate value of one of the three basic char types is UB: there are some Defect Reports about it (DR #240 and #616), and the C++14 wording is different from C++11 and earlier, and seems to have moved the specification of UB to some other part of the standard.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

You should remember that there is no default initial value for automatic variables defined in the C++11 standard.

In practice, such a variable would contain some garbage value (if it sits in a processor register, the previous value of it; if it sits in a slot of the call stack, the former value at that location) which could be 0 (or something else).

Details are implementation specific and would vary with the compiler, the run, the optimization flags.

Read about undefined behavior, notably Lattner's blog: What every programmer should know about undefined behavior. Be really scared of them.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547