0
#include <stdio.h>

void main(int x)
{

    printf("%d",x);
    
    return 0;
}

If we print x value in main() function it will show 0 and as the default value of int is 0. when i add int x as a parameter in main() it prints x value is 1. Why?

r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • 2
    Does this answer your question? [What does int argc, char \*argv\[\] mean?](https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean) – Uriya Harpeness Nov 24 '20 at 13:24
  • 1
    I have never seen a `main` like that before, but i think it will give 1, as the first arg for main can be `argc` – csavvy Nov 24 '20 at 13:24
  • 1
    `main` receives two parameters, `argc` and `argv`, look here for their meaning: https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean. – Uriya Harpeness Nov 24 '20 at 13:25
  • "as the default value of int is 0" Why do you think that? There is no "default value". Accessing an uninitialized variable is undefined behavior. – William Pursell Nov 24 '20 at 13:38
  • @WilliamPursell Unless it's static – klutt Nov 24 '20 at 13:43

2 Answers2

1

Afaik in a hosted environment the only valid main prototypes are:

void main(void);
void main(int argc, char* argv[]);

Anything else (including your example) is undefined behavior.

At local scope a variable is unitialized. Reading from it results in undefined behavior.

At global scope an int variable is default initialized to 0.

bolov
  • 72,283
  • 15
  • 145
  • 224
1

as the default value of int is 0

No it's not. However, it's kind of the default value for all static variables, like global variables, but irregardless of their type. Variables with automatic storage have indeterminate values and reading them before they are initialized causes undefined behavior.

when i add int x as a parameter in main() it prints x value is 1. Why?

Well, int main(int) is not a valid signature. The two allowed are int main(void) and int main(int, char**). And when you choose the second, then the first argument will be the number of arguments passed to the program. And the first argument is the name of the program. So this code:

int main(int argc, char **argv) {
    puts(argv[0]);
}

will print something like

$ ./a.out
a.out
klutt
  • 30,332
  • 17
  • 55
  • 95