I think we need to know two points at this stage:
- There is nothing different between regular variables and structs, if they are at local scope i.e
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 i.e. initialised as if they had static storage duration
. But that's not the case when none of the members are initialised.
- 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 i.e. 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