CS102: Argc/Argv

  • argc (The Argument Counter) and argv (The Argument Values) represent parameters of the int main() {} function.

    • This allows for the main() function to accept and process command-line arguments from the user.


Syntax

  • The signature of main() once int argc and char **argv have been passed in.

ex. Skeleton Argc Argv

//User Command Line: ./[program name/path/Argument1] [Argument2] [Argument3]

int main (int argc, char **argv) {
	//Code
}
  • argc (Argument Count): Is an integer that represents the number of arguments passed to the program, including the program's name itself.

  • argv (Argument Vector): An array of C-style strings (character pointers), where each string represents a command-line argument.


Explanation: argc and argv

  1. argc:

    • Includes the program name as the first argument.

    • Its value is always at least 1 (even if no additional arguments are provided).

  2. argv:

    • argv[0] is the program's name or path.

    • argv[1] to argv[argc-1] are the additional arguments provided by the user on the command line.


Example for Processing Command-Line Arguments:

  • Command Line Execution (Same for both): ./program Hello World

  • Output (Same for both):

    Number of arguments: 3

    • {./program, Hello, World}

    Argument 0: ./program

    • Argument 1 is ALWAYS the name or path of the program which will be executed.

    Argument 1: Hello


    Argument 2: World


#include <iostream>

using namespace std;

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

    // Print the number of arguments
    cout << "Number of arguments: " << argc << endl;

    // Loop through and print each argument
    for (int i = 0; i < argc; ++i) {        
	cout << "Argument " << i << ": " << argv[i] << endl;
    }

    return 0;
}
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    //Prints out the number of arguments
    cout << "Number of arguments: " << argc << endl;
    //Loops through and prints each argument
	//NOTICE: argv itself is a pointer to argv[0], and each argv[i] is a pointer to a char array.
    for (int i = 0; i < argc; ++i) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
    return 0;
}

Notice: The difference between char* argv[] and char** argv

  • char* argv[]: Refers to a pointer to a memory address (this is the address of a character array, or string)

  • char** argv: Indicates that a pointer is pointing to an array of pointers

  • THE MAIN TAKEAWAY HERE IS THAT THESE ARE FUNCTIONALLY EQUIVALENT!



Practical Uses:

  1. Passing Input: Command-line arguments can be used to pass data to the program during execution.

  2. Configuration: Programs can be configured or customized using arguments (e.g., filenames, modes).

  3. Utilities: Many command-line utilities, such as compilers or scripts, use these arguments to provide functionality.