I read that if a variable/pointer is declared outside a function it will be assigned a value of zero/NULL by default. I worte a code to test the same and found it is very much correct:
Code:
/* Values of un initialized variables and pointers when declared inside or outside a function */
#include<stdio.h>
int j;
int *ptr;
int main(void) {
int k;
int *ptr2;
printf("j is declared outside main %d\n", j);
printf("ptr is declared outside main %d\n", ptr);
printf("k is declared inside main %d\n", k);
printf("ptr2 is declared inside main %d\n", ptr2);
return 0;
}
result i get is :
Code:
$ ./prog1
j is declared outside main 0
ptr is declared outside main 0
k is declared inside main -1208533004
ptr2 is declared inside main -1208408144
My question is what is the logic behind this behaviour? why won't variables that are declared inside a function also initialized to zero/NULL automatically?