Why there is no error when passing command line arguments when declaring main as `int main(void)`?
Because the C compiler and the command line interpreter (or whatever is used to invoke your program) are different things.
The C language allows various ways how main () could be declared.
The command line interpreter will make any arguments available to the program. If the program ignores them, that's none of its business.
The command line interpreter doesn't even know that you used C to compile your program. On my computer, the program could be written in C, C++, Objective-C, Objective-C++, Swift, Fortran, Ada, and so on. Each of these compilers may or may not do things to accept commands from the command line.
Not checking the specification nor compiled result, it will cause no error because the C runtime will get the arguments and pass them to main()
, but this type of main()
will ignore the passed arguments, and if it is caller's duty to clean up the memory (stack) used as the arguments, it will cause no problems just as getting some arguments and not using them in the code.
This code won't emit errors in C:
void hello(); // in C, the compiler won't check arguments
int main() {
hello(1); //no error
return 0;
}
void hello(void) {
//something
}
Because ./a.out something something
is not directly calling your main function. THe main function is being called by the c runtime library. The command line arguments are placed in a region somewhere on the stack (very beginning) by the loader/c runtime. It is upto you if you want to access these arguments or not.
Plus as pointed out in one of the comments as well at least one command line argument is always passed anyways (the name of the program ./a.out
to be precise) - so you must have wondered about an error in that case as well.