Search code examples
cintegerinitializationprintfundefined-behavior

Why prinf prints random number?


This is my code. Why does C prints a random number like 3321856? I know it's because it's an empty variable, but why this number? is it random or has some reason?

#include <stdio.h>

void main()
{
    int a;
    printf("%d", a);
}


Solution

  • For starters, the function main without parameters according to the C Standard shall be declared as follows.

    int main( void )
    

    Secondly, the variable a is not initialized and has an indeterminate value, so the program invokes undefined behavior.

    You need to initialize the variable a with a value before outputting that value, or the output will be undefined.

    The variable a is defined in the outer block scope of the function main without the storage class specifier static. So it has automatic storage duration. Such variables are not implicitly initialized.