Example 1
// This is the classic form of the main() function // with argument parameters. We have added a simple // for loop to output the parameters for illustration. #include <iostream> int main(int argc, const char* argv[]) { for (int i = 0; i < argc; ++i) { std::cout << argv[i] << std::endl; } return 0; }
Suppose that this program is compiled into an executable called "MyProg.exe" and is located in the folder "C:\Dev\C++\" as shown here.
Below, we give the command to execute the program with three argument parameters. The program is "MyProg.exe" and is located in "C:\Dev\C++" with the three arguments "arg1 arg2 arg3" appended. The first "C:\>" is just the command prompt for our C drive.
C:\>C:\Dev\C++\MyProg.exe arg1 arg2 arg3
The command prompt for this is shown here:
For clarity, the output is shown below with those argument parameters used. Note that the first argument is the executable with its path location.
C:\Dev\C++\MyProg.exe arg1 arg2 arg3
Example 2
// We do not need to have our main() function take parameters. // This simpler version is also standard in C++. // Returning 0 from main indicates success and 1 indicates failure. int main() { // Some code bool bHasError(false); // Some code if (bHasError) { return 1; } // Some code return 0; }
Example 3
// This is the same as Example 2 above. // However, the return numbers are given as names for clarity. // These values are defined in stdlib.h. This file, or one // that includes it such as iostream, must be included. #include <iostream> int main() { // Some code bool bHasError(false); // Some code if (bHasError) { return EXIT_FAILURE; } // Some code return EXIT_SUCCESS; }
Example 4
// This example is the simplest main() function signature. // It can be used in Visual C++, but it is not in the C++ standard. void main() { // Some code }
© 20072025 XoaX.net LLC. All rights reserved.