cdefinitionlocal-variables

Automatic initalization of local variables


According to the C standard, the local variables declared in the local scope would carry garbage value until they are explicitly initialized. In contrast to that, if the variable is declared in the global scope, it's implicitly defined to 0.

All of that is being holding true only when I'm declaring one or two variables, such as int w, x. But when I'm declaring three or more variables, few are automatically being defined to 0. Which is completely against the standard, I believe.

Note: I ran it multiple times and it does that every single time as if it's deliberate.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int w, x, y, z;
    printf("%d %d %d %d\n", w, x, y, z);

    return EXIT_SUCCESS;
}

GCC's Output: 0 0 1623616696 32764

Clang's Output: 849564872 0 0 29759


Solution

  • The variables rightfully so contains undetermined values.

    Compare it with the language design in java: object fields are zeroed (or null or false) and local variables are also uninitialized. Here the compiler gives a message when some variable might not be initialized.

    That is intentional. So the programmer does not erringly work with default values when they forget setting a value.

    Now in C one should set a correct warning level too. And declaration at first use (and possibly immediate initialisation) I grew fond of too.

    The effect you saw might be zeroed heap, and previous calls messing up local variables with prior return addresses and other garbage. Keep to lint quality.