Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"struct a a1 = {0};" different from "struct a a2 = {5};" why?

Tags:

c

struct

If struct a a1 = {0}; initializes all the elements (of different types) of a structure to zero, then struct a a2 = {5}; should initialize it to 5.. no?

#include <stdio.h>

typedef struct _a {
    int i;
    int j;
    int k;
}a;

int main(void)
{
    a a0;
    a a1 = {0};
    a a2 = {5};

    printf("a0.i = %d \n", a0.i);
    printf("a0.j = %d \n", a0.j);
    printf("a0.k = %d \n", a0.k);

    printf("a1.i = %d \n", a1.i);
    printf("a1.j = %d \n", a1.j);
    printf("a1.k = %d \n", a1.k);

    printf("a2.i = %d \n", a2.i);
    printf("a2.j = %d \n", a2.j);
    printf("a2.k = %d \n", a2.k);

    return 0;
}

The uninitialized struct contains garbage values

a0.i = 134513937
a0.j = 134513456
a0.k = 0 

The initialized to 0 struct contains all elements initialized to 0

a1.i = 0 
a1.j = 0 
a1.k = 0 

The initialized to 5 struct contains only the first element initialized to 5 and the rest of the elements initialized to 0.

a2.i = 5 
a2.j = 0 
a2.k = 0

Would a2.j and a2.k always guaranteed to initialize to 0 during a a2 = {5}; (or) is it an undefined behavior

OTOH, why am I not seeing all the elements of s2 initialized to 5. How is the struct initialization is done during {0} and how is it different when {5} is used?

like image 923
Sangeeth Saravanaraj Avatar asked Nov 28 '22 09:11

Sangeeth Saravanaraj


2 Answers

The omitted values will be always initialized to zero, because the standard says so. So you have essentially

struct a a1 = { 0, 0, 0 };

and

struct a a2 = { 5, 0, 0 };

which is of course different.

like image 36
Gunther Piez Avatar answered Dec 21 '22 07:12

Gunther Piez


Reference:

C99 Standard 6.7.8.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

[EDIT]

Static objects and implicit initialization:

The storage duration of an object determines the lifetime of an object.
There are 3 storage durations:
static, automatic, and allocated

variables declared outside of all blocks and those explicitly declared with the static storage class specifier have static storage duration. Static variables are initialized to zero by default by the compiler.

Consider the following program:

#include<stdio.h>

int main()
{
    int i;
    static int j;
    printf("i = [%d]",i);
    printf("j = [%d]",j);

    return 0;
}

In the above program, i has automatic storage and since it is not explicitly initialized its value is Undefined.
While j has static storage duration and it is guaranteed to be initialized to 0 by the compiler.

like image 70
Alok Save Avatar answered Dec 21 '22 07:12

Alok Save