简体   繁体   中英

Default values in struct c [duplicates]

What does the code below print when running the function print_test()?

struct test {
  int a, b, c;
};

void print_test(void) {
  struct test t = {1};
  printf("%d/%d/%d", t.a, t.b, t.c);
}

Solution 1\\0\\0

Why are b and c initialized to zero even though I did not do it? Are there any default values for the struct? However, the struct is not global and the member is not static. Why are they automatically zero-initialized? And if the data type were not int another data type to which value will be initialized?

If you don't specify enough initializers for all members of a struct, you'll face Zero initialization , which will initialize remaining members to 0 . I think by today's standards this seems a bit odd, especially because C++'s initialization syntax has evolved and matured a lot over the years. But this behavior remains for backwards-compatibility.

I think we need to know two points at this stage:

  1. There is nothing different between regular variables and structs, if they are at local scope ie automatic storage duration . They will contain garbage values. Using those values could invoke undefined behaviour.

The only thing that makes structs different is that if you initialise at least one of the members, the rest of the members will get set to zero ie initialised as if they had static storage duration . But that's not the case when none of the members are initialised.

  1. It depends on your declaration. If your declaration is outside any function or with the static keyword (more precisely, has static storage duration ), the initial value of x is a null pointer (which may be written either as 0 or as NULL).

If it's inside a function ie it has automatic storage duration , its initial value is random (garbage).

consider the following code:

#include<stdio.h>
#include<unistd.h>

struct point {
    int x, y;
    char a;
    double d;
};    
typedef struct point Point;

void main(){ 
    Point p1;
    printf("\nP1.x: %d\n", p1.x);
    printf("\nP1.y: %d\n", p1.y);
    printf("\nP1.a: %d\n", p1.a);
    printf("\nP1.d: %lf\n", p1.d);

    Point p2 = {1};
    printf("\nP2.x: %d\n", p2.x);
    printf("\nP2.y: %d\n", p2.y);
    printf("\nP2.a: %d\n", p2.a);
    printf("\nP2.d: %lf\n", p2.d);
}

The output is :

P1.x: 0

P1.y: 66900

P1.a: 140

P1.d: 0.000000

P2.x: 1

P2.y: 0

P2.a: 0

P2.d: 0.000000

A Good read: C and C++ : Partial initialization of automatic structure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM