jeudi 21 février 2019

C++ 11 multiple struct zero initialization

I discovered this strange in the course of development. Why does the default struct initialization behave differently in the following cases.

Case 1 (works as expected):

struct msg
{
   int a[100];
};

void test_compare_zero(void)
{
    struct msg m1 = {0};
    struct msg m2 = {0};

    if (0 == memcmp(&m1, &m2, sizeof(struct msg)))
    {
        printf("structs are equal");
    }
}

Case 2 (does not work as expected):

struct msg
{
   int a[100];
};

void test_compare_zero(void)
{
    struct msg m1 = {0}, m2 = {0};

    if (0 == memcmp(&m1, &m2, sizeof(struct msg)))
    {
        printf("structs are equal");
    }
}

My compiler version:

gcc --version

gcc (GCC) 7.3.1 20180712 (Red Hat 7.3.1-6)

Aucun commentaire:

Enregistrer un commentaire