4
votes

Why following code produced 0 as output? In my understanding, it is default initialization (not value initialization) so value should be random.

#include <stdio.h>
#include<iostream>
#include<memory>

using namespace std;

struct A 
{

    int i;
    int j;
};


int main()
{
    A a;

    cout << " i is " << a.i << endl;

    return 0;
}

from cppreference:

The effects of default initialization are:

if T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;

if T is an array type, every element of the array is default-initialized;

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

2
Can't 0 be drawn in a random draw? - StoryTeller - Unslander Monica
isnt 0 as random as any other number? - 463035818_is_not_a_number
Why do you think, that 0 is an invalid random value? - Algirdas Preidžius
its a common misunderstanding in c++ that if there is a red traffic light telling you not to cross the street, that there must be a car crossing your path. The reality is: the red light just tells you that there might be a car crossing your path, so unless you want to take the risk you better go with green - 463035818_is_not_a_number

2 Answers

3
votes

What value you get for a.i is not defined, you should expect to get any value.

Depening on the system, the used std library, the compiler, the compiler flags, ... some parts of the memory (e.g. the stack) might be initialized with 0, but there is no guarantee for that.

This is also true for gcc, in your simple example your might always get 0, but if you turn off optimizations -O0 and compile the following code:

#include <iostream>

struct A 
{
  int i;
  int j;
};


int foo() {
  A a;
  const int b = a.i;
  a.i = 123;
  return b;
}

int main() {
  const int n1 = foo();
  const int n2 = foo();
  std::cout << n1 << " " << n2 << std::endl;
  return 0;
}

Then (depending on the os, std library, cpu ...) you will have the following output:

0 123

In both cases a.i is uninitialized, for the first call the a.i holds some "random" number, for the second call, a might be created at the same location, and as of that this part of the memory might still hold 123. The reason for that is that A is created on the stack, and the subsequent calls to off foo will most likely cause a to be located on the same memory address on the stack.

0
votes

Based on discussion, experiment. It is undefined behavior. POD have no special treatment in default initialization.

clang, MSVC always gave random value but gcc always gave 0. Afterall, undefined is undefined.