Site icon Learn C++

The Main Function of a C++ Program

The source code written in C++ must be compiled (i.e. translated to the machine code) by one or another compiler such as Embarcadero RAD Studio C++ compilers before in can be runned. In general, there are two types of the resulting machine code: library and main executable (hereinafter simply executable). This post will briefly cover the later of these two.

When an executable produced from a C++ source code starts an operating system calls the global function main(). There only two possible signatures of the main() function:

[crayon-6621caa5b29a2112446899/]

In case (1) the main() function does not accepts any arguments. By defining the main() function this way, it’s not possible to access the command line arguments which are passed to an executable upon the start. On the contrary, in the case (2), the program argument count and the program argument values are available from within the main() function through the argc and argv variables accordingly.

In both cases the value of type int returned by the main() function indicates so called exit status. Usually, this value can be obtained by using the command shell facility immediately after the program exit. By convention, the returned value of 0 indicates a successful program completion, while nonzero value indicates a failure. Often the different nonzero values are used to distinguish between the failures. If no value is returned explicitly an operating system will receive zero exit status indicating successful completion implicitly.

Accessing the command line arguments

As mentioned above, it’s possible to access command line arguments passed to an executable upon start if the main() function defined with two arguments. For example, the C++ program that nicely prints both the path of the executable and the arguments specified upon the start via the command line might looks as follow:

[crayon-6621caa5b29aa997390355/]

Please note, that the argc and argv are declared as constants, which allows to hedge against theirs accidental modification. Also note, that the value of argc is always positive, because the value of argv[0] is always denotes the path of the executable specified when it starts. Finally, if there are arguments passed to the executable through the command line, they are always accessible as a sequence in range of [argv + 1, argv + argc).

Exit mobile version