C++ Main Function Arguments (argc, argv)

In C++, the main function can accept arguments from the command line using two parameters: argc (argument count) and argv (argument vector). This allows programs to process input directly from the user when executing the program.

1. Syntax

The main function can be defined as follows to accept command-line arguments:

C++
Syntax of main with arguments
int main(int argc, char *argv[]) {
    // code
    return 0;
}

2. Example: Using argc and argv

This example demonstrates how to access command-line arguments passed to the program.

C++
Example: Main function arguments
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
    cout << "Number of arguments: " << argc << endl;
    for (int i = 0; i < argc; i++) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
    return 0;
}

3. How it Works

- argc holds the number of command-line arguments passed, including the program name. - argv is an array of C-style strings (char*) representing each argument. - argv[0] is always the program name, and argv[1] to argv[argc-1] are the arguments provided by the user.

4. Common Mistakes

1. Forgetting that argv is an array of char pointers, not strings. 2. Accessing argv[i] without checking if i < argc. 3. Miscounting arguments, especially the program name.

Conclusion

C++ main function arguments (argc, argv) allow programs to accept input from the command line. Proper handling enables flexible and dynamic programs that can respond to user input without modifying code.