I was playing with the single line declaration and initialization of multiple variables and notices something out of ordinary in C
#include <stdio.h>
int main() {
int a, c, d, e = 0;
printf("a = %d, c = %d, d = %d, e = %d", a, c, d, e);
}
So the output of the above program was
a = 2961408, c = 0, d = 4200720, e = 0
Easy since e
is assigned 0
and rest all may be garbage value but c has the value 0. I changed the code to
#include <stdio.h>
int main() {
int a, b, c, d, e = 0;
printf("a = %d, b = %d, c = %d, d = %d, e = %d", a, b, c, d, e);
}
and this time the output was:
a = 2297856, b = 0, c = 4200736, d = 4200848, e = 0
Again the second variable was initialized as 0
[Here b
, previously c
] along with e
and rest all are garbage.
And the same thing was noticed for 3
, 4
, 5
, 6
, 7
, and so on variables every time the second variable in the declaration is initialized the value 0
along with the last variable.
This is not the case of initialization of last variable but if I assign any variable after the second variable with value 0
. My second variable get 0
as it's initialization value. Is it something wrong with my compiler or is there some logic behind this in C?
#include <stdio.h>
int main() {
int a, b, c, d, e, g = 10, f;
printf("a = %d, b = %d, c = %d, d = %d, e = %d, g = %d, f = %d", a, b, c, d, e, g, f);
}
Output:
a = 3702784, b = 0, c = 4200752, d = 4200864, e = 6422400, g = 10, f = 4200752
[P.S. My C compiler is gcc (MinGW.org GCC Build-2) 9.2.0 ]