Page 73 - C-Language
P. 73

Chapter 9: Command-line arguments




        Syntax



            •  int main(int argc, char *argv[])


        Parameters




          Parameter     Details

                        argument count - initialized to the number of space-separated arguments given
          argc
                        to the program from the command-line as well as the program name itself.


                        argument vector - initialized to an array of char-pointers (strings) containing the
          argv
                        arguments (and the program name) that was given on the command-line.



        Remarks


        A C program running in a 'hosted environment' (the normal type — as opposed to a 'freestanding
        environment') must have a main function. It is traditionally defined as:


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


        Note that argv can also be, and very often is, defined as char **argv; the behavior is the same.
        Also, the parameter names can be changed because they're just local variables within the
        function, but argc and argv are conventional and you should use those names.


        For main functions where the code does not use any arguments, use int main(void).

        Both parameters are initialized when the program starts:


            •  argc is initialized to the number of space-separated arguments given to the program from the
              command-line as well as the program name itself.
            •  argv is an array of char-pointers (strings) containing the arguments (and the program name)
              that was given on the command-line.
            •  some systems expand command-line arguments "in the shell", others do not. On Unix if the
              user types myprogram *.txt the program will receive a list of text files; on Windows it will
              receive the string "*.txt".

        Note: Before using argv, you might need to check the value of argc. In theory, argc could be 0, and
        if argc is zero, then there are no arguments and argv[0] (equivalent to argv[argc]) is a null pointer.
        It would be an unusual system with a hosted environment if you ran into this problem. Similarly, it
        is possible, though very unusual, for there to be no information about the program name. In that
        case, argv[0][0] == '\0' — the program name may be empty.




        https://riptutorial.com/                                                                               49
   68   69   70   71   72   73   74   75   76   77   78