First snippet:
#include<stdio.h>
int main(int argc, char **argv)
{
int i;
for(i=1; i<argc; i++)
printf("%s\n", argv[i]);
return 0;
}
load time input :
./a.out devang samir
output:
devang
samir
Second snippet:
#include<stdio.h>
int main(int argc, int *argv)
{
int i;
for(i=1; i<argc; i++)
printf("%s\n", argv[i]);
return 0;
}
load time input :
./a.out devang samir
output:
devang
samir
in both case, i got output same, but why?
The C11
standard specifies the function signature for main()
in chapter §5.1.2.2.1 as
The function called at program startup is named
main
. The implementation declares no prototype for this function. It shall be defined with a return type ofint
and with no parameters:int main(void) { /* ... */ }
or with two parameters (referred to here as
argc
andargv
, though any names may be used, as they are local to the function in which they are declared):int main(int argc, char *argv[]) { /* ... */ }
or equivalent;[...]
and regarding the constrains,
If the value of
argc
is greater than zero, the array membersargv[0]
throughargv[argc-1]
inclusive shall contain pointers to strings,[...]
Then, in your second case,
int main(int argc, int *argv)
char*
and int
( for argv[n]
, in general) are being different types altogether (i.e, not compatible type), your second program invokes undefined behavior.
To elaborate, in case of the functions without having a prototype, the parameters passed to the function while calling should exactly match the type of expected arguments.
Quoting the standard, chapter §6.5.2.2
[...] If the function is defined with a type that does not include a prototype, and the types of the arguments after promotion are not compatible with those of the parameters after promotion, the behavior is undefined.