Search code examples
cinitializationimplicit

`int main(i){ printf("i = %d\n", i); }` i value is 1. why ? please explain?


Why it prints I value as 1, can someone please explain?

#include<stdio.h>
int main(i)
{ 
    printf("i = %d\n", i); 
}

output i = 1.


Solution

  • C is interpreting i as type int - if you don't declare a variable, its default type is int. By coincidence, main is used to being called as int main(int argc, char **argv), so your i (which is now an int) fits into that first parameter. main will allow you to call it with only one argument, but this is technically undefined behavior - don't do it.

    The first value, argc, is a number detailing how many command line arguments were given. (The second is the strings of those arguments.) In your case, only one command-line argument was given, that being the name of the executable (probably ./a.out).

    Try running your code with ./a.out some strings here - you'll notice different values printing.