#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?
#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?
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
.
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