Why can C main function be coded with or without parameters?

前端 未结 5 728
离开以前
离开以前 2020-12-06 12:14

Just wondering why this

int main(void){}

compiles and links

and so does this:

int main(int argc, char **argv){}
         


        
5条回答
  •  广开言路
    2020-12-06 12:44

    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 of int and with no parameters:

    int main(void) { /* ... */ }

    or with two parameters (referred to here as argc and argv, 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; or in some other implementation-defined manner.

    Regarding the parameters:

    The first counts the arguments supplied to the program and the second is an array of pointers to the strings which are those arguments. These arguments are passed to the program by the command line interpreter. So, the two possibilities are handled as:

    1. If no parameters are declared: no parameters are expected as input.

    2. If there are parameters in main() ,they should:

      • argc is greater than zero.
      • argv[argc] is a null pointer.
      • argv[0] through to argv[argc-1] are pointers to strings whose meaning will be determined by the program.
      • argv[0] will be a string containing the program's name or a null string if that is not available. Remaining elements of argv represent the arguments supplied to the program. In cases where there is only support for single-case characters, the contents of these strings will be supplied to the program in lower-case.

    In memory:

    they will be placed on the stack just above the return address and the saved base pointer (just as any other stack frame).

    At machine level:

    they will be passed in registers, depending on the implementation.

提交回复
热议问题