Thursday, 12 September 2013

In C, are global integers always zero-initialized or why does this code give no warnings?

In C, are global integers always zero-initialized or why does this code
give no warnings?

I'm having trouble understanding where exactly a variable is initialized
in a recursive function involving string pointers. I found the following C
code in some lecture materials:
#include <stdio.h>
int a, b;
void magic(char s[]) {
int ch;
if ((ch = s[a++])) {
magic(s);
s[++b] = ch;
} else
b = -1, a = 0;
}
int main() {
char s[] = "abcdefghijk";
magic(s);
printf("%c\n", *s);
return 0;
}
When compiling the file with gcc -Wall --pedantic the compiler gives no
warnings.
I would somehow expect a warning about an uninitialized variable a. When
the function magic() is called first, both a and b should be uninitialized
especially when we hit the line if((ch = s[a++])).
Can someone explain to me, why gcc is not complaining about this? Why are
both a and b initialized to zero at the first time magic() is called? Are
global variables generally zero-initialized? If so why and why did I miss
this fact completely?

No comments:

Post a Comment