0

In the old days structure like that:

typedef struct A {
    int m_i;
    int m_j;
} A;

Allocated on the heap or declared locally in a function without being memset would have its members uninitialized.

However, to my utter surprise this little program shows it is always set to 0.

#include <stdio.h>

typedef struct A {
    int m_i;
    int m_j;
} A;

void f(const A& a) {
    printf("i=%i, j=%i\n", a.m_i, a.m_j);
}

void y() {
    f({10});
}

int main() {
    y();
    return 0;
}

Built using g++ -std=c++11 a.cpp

I would just in case defined a constructor to make sure they are zero, but my various tests show (using code found on the internet) that I don't have to.

Is this a shear coincidence or extended initializer list is a guarantor of having memory being memset?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Grzegorz
  • 3,207
  • 3
  • 20
  • 43

1 Answers1

4
typedef struct A {
    int m_i;
    int m_j;
} A;

is an aggregate. When you initialize an aggregate with a braced-init-list it uses each element in the list to initialize each member of the aggregate. If you don't provide enough elements in the braced-init-list then each subsequent member is guaranteed to be value initialized, which for fundamental types means they are zero initialized..

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Would you be able to provide a reference, please? I have noticed that but I don't know if this is a matter of well defined behavior or particular compiler stuff. – Grzegorz Oct 03 '18 at 16:22
  • @Grzegorz Reference: https://stackoverflow.com/questions/25804188/zero-initialization-of-pod-types – NathanOliver Oct 03 '18 at 16:28