`main` function and command-line arguments (C++) (2023)

  • Article
  • 8 minutes to read

All C++ programs must have a main function. If you try to compile a C++ program without a main function, the compiler raises an error. (Dynamic-link libraries and static libraries don't have a main function.) The main function is where your source code begins execution, but before a program enters the main function, all static class members without explicit initializers are set to zero. In Microsoft C++, global static objects are also initialized before entry to main. Several restrictions apply to the main function that don't apply to any other C++ functions. The main function:

  • Can't be overloaded (see Function overloading).
  • Can't be declared as inline.
  • Can't be declared as static.
  • Can't have its address taken.
  • Can't be called from your program.

The main function signature

The main function doesn't have a declaration, because it's built into the language. If it did, the declaration syntax for main would look like this:

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

If no return value is specified in main, the compiler supplies a return value of zero.

Standard command-line arguments

The arguments for main allow convenient command-line parsing of arguments. The types for argc and argv are defined by the language. The names argc and argv are traditional, but you can name them whatever you like.

The argument definitions are as follows:

argc
An integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.

(Video) What does int argc, char* argv[] mean?

argv
An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1], and argv[argc] is always NULL.

For information on how to suppress command-line processing, see Customize C++ command-line processing.

Note

By convention, argv[0] is the filename of the program. However, on Windows it's possible to spawn a process by using CreateProcess. If you use both the first and second arguments (lpApplicationName and lpCommandLine), argv[0] may not be the executable name. You can use GetModuleFileName to retrieve the executable name, and its fully-qualified path.

Microsoft-specific extensions

The following sections describe Microsoft-specific behavior.

The wmain function and _tmain macro

If you design your source code to use Unicode wide characters, you can use the Microsoft-specific wmain entry point, which is the wide-character version of main. Here's the effective declaration syntax for wmain:

int wmain();int wmain(int argc, wchar_t *argv[]);

You can also use the Microsoft-specific _tmain, which is a preprocessor macro defined in tchar.h. _tmain resolves to main unless _UNICODE is defined. In that case, _tmain resolves to wmain. The _tmain macro and other macros that begin with _t are useful for code that must build separate versions for both narrow and wide character sets. For more information, see Using generic-text mappings.

(Video) C++ Tutorial for Beginners 13 - Passing Parameters and Arguments in Function

Returning void from main

As a Microsoft extension, the main and wmain functions can be declared as returning void (no return value). This extension is also available in some other compilers, but its use isn't recommended. It's available for symmetry when main doesn't return a value.

If you declare main or wmain as returning void, you can't return an exit code to the parent process or the operating system by using a return statement. To return an exit code when main or wmain is declared as void, you must use the exit function.

The envp command-line argument

The main or wmain signatures allow an optional Microsoft-specific extension for access to environment variables. This extension is also common in other compilers for Windows and UNIX systems. The name envp is traditional, but you can name the environment parameter whatever you like. Here are the effective declarations for the argument lists that include the environment parameter:

int main(int argc, char* argv[], char* envp[]);int wmain(int argc, wchar_t* argv[], wchar_t* envp[]);

envp
The optional envp parameter is an array of strings representing the variables set in the user's environment. This array is terminated by a NULL entry. It can be declared as an array of pointers to char (char *envp[]) or as a pointer to pointers to char (char **envp). If your program uses wmain instead of main, use the wchar_t data type instead of char.

The environment block passed to main and wmain is a "frozen" copy of the current environment. If you later change the environment by making a call to putenv or _wputenv, the current environment (as returned by getenv or _wgetenv and the _environ or _wenviron variable) will change, but the block pointed to by envp won't change. For more information on how to suppress environment processing, see Customize C++ command-line processing. The envp argument is compatible with the C89 standard, but not with C++ standards.

Example arguments to main

The following example shows how to use the argc, argv, and envp arguments to main:

// argument_definitions.cpp// compile with: /EHsc#include <iostream>#include <string.h>using namespace std;int main( int argc, char *argv[], char *envp[] ){ bool numberLines = false; // Default is no line numbers. // If /n is passed to the .exe, display numbered listing // of environment variables. if ( (argc == 2) && _stricmp( argv[1], "/n" ) == 0 ) numberLines = true; // Walk through list of strings until a NULL is encountered. for ( int i = 0; envp[i] != NULL; ++i ) { if ( numberLines ) cout << i << ": "; // Prefix with numbers if /n specified cout << envp[i] << "\n"; }}

Parsing C++ command-line arguments

The command line parsing rules used by Microsoft C/C++ code are Microsoft-specific. The runtime startup code uses these rules when interpreting arguments given on the operating system command line:

  • Arguments are delimited by white space, which is either a space or a tab.

    (Video) 21: Using the arguments of the main function (C++) - Easy

  • The first argument (argv[0]) is treated specially. It represents the program name. Because it must be a valid pathname, parts surrounded by double quote marks (") are allowed. The double quote marks aren't included in the argv[0] output. The parts surrounded by double quote marks prevent interpretation of a space or tab character as the end of the argument. The later rules in this list don't apply.

  • A string surrounded by double quote marks is interpreted as a single argument, which may contain white-space characters. A quoted string can be embedded in an argument. The caret (^) isn't recognized as an escape character or delimiter. Within a quoted string, a pair of double quote marks is interpreted as a single escaped double quote mark. If the command line ends before a closing double quote mark is found, then all the characters read so far are output as the last argument.

  • A double quote mark preceded by a backslash (\") is interpreted as a literal double quote mark (").

  • Backslashes are interpreted literally, unless they immediately precede a double quote mark.

  • If an even number of backslashes is followed by a double quote mark, then one backslash (\) is placed in the argv array for every pair of backslashes (\\), and the double quote mark (") is interpreted as a string delimiter.

  • If an odd number of backslashes is followed by a double quote mark, then one backslash (\) is placed in the argv array for every pair of backslashes (\\). The double quote mark is interpreted as an escape sequence by the remaining backslash, causing a literal double quote mark (") to be placed in argv.

Example of command-line argument parsing

The following program demonstrates how command-line arguments are passed:

// command_line_arguments.cpp// compile with: /EHsc#include <iostream>using namespace std;int main( int argc, // Number of strings in array argv char *argv[], // Array of command-line argument strings char *envp[] ) // Array of environment variable strings{ int count; // Display each command-line argument. cout << "\nCommand-line arguments:\n"; for( count = 0; count < argc; count++ ) cout << " argv[" << count << "] " << argv[count] << "\n";}

Results of parsing command lines

The following table shows example input and expected output, demonstrating the rules in the preceding list.

(Video) C++ - Command line arguments and user keyboard input

Command-line inputargv[1]argv[2]argv[3]
"abc" d eabcde
a\\b d"e f"g ha\\bde fgh
a\\\"b c da\"bcd
a\\\\"b c" d ea\\b cde
a"b"" c dab" c d

Wildcard expansion

The Microsoft compiler optionally allows you to use wildcard characters, the question mark (?) and asterisk (*), to specify filename and path arguments on the command line.

Command-line arguments are handled by an internal routine in the runtime startup code, which by default doesn't expand wildcards into separate strings in the argv string array. You can enable wildcard expansion by including the setargv.obj file (wsetargv.obj file for wmain) in your /link compiler options or your LINK command line.

For more information on runtime startup linker options, see Link options.

Customize C++ command-line processing

If your program doesn't take command-line arguments, you can suppress the command-line processing routine to save a small amount of space. To suppress its use, include the noarg.obj file (for both main and wmain) in your /link compiler options or your LINK command line.

Similarly, if you never access the environment table through the envp argument, you can suppress the internal environment-processing routine. To suppress its use, include the noenv.obj file (for both main and wmain) in your /link compiler options or your LINK command line.

Your program might make calls to the spawn or exec family of routines in the C runtime library. If it does, you shouldn't suppress the environment-processing routine, since it's used to pass an environment from the parent process to the child process.

See also

Basic concepts

FAQs

What is function with command line arguments in C? ›

What are Command Line Arguments in C? Command line arguments are the arguments which the user gives from the operating system's command line during the time of execution. Earlier, we used main() functions without arguments. These command line arguments are handled by the main() function.

What are the command line arguments in C++? ›

Properties of Command-Line Arguments

They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the code. argv[argc] is a NULL pointer. argv[0] holds the name of the program.

Can we pass argument in main function in C++? ›

Yes, we can give arguments in the main() function. Command line arguments in C are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution. The argc and argv are the two arguments that can pass to main function.

How do you pass parameters to main () function? ›

There are two ways by which we can pass the parameters to the functions:
  1. Call by value. Here the values of the variables are passed by the calling function to the called function. ...
  2. Call by reference. Here, the address of the variables are passed by the calling function to the called function.

What is main function in C? ›

Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.

What is an example of command line argument? ›

Let's see the example of command line arguments where we are passing one argument with file name.
  • #include <stdio.h>
  • void main(int argc, char *argv[] ) {
  • printf("Program name is: %s\n", argv[0]);
  • if(argc < 2){
  • printf("No argument passed through command line.\n");
  • }
  • else{
  • printf("First argument is: %s\n", argv[1]);

What are the 3 ways to pass C++ arguments to a function? ›

Parameter Passing in C++

There are three parameter-passing modes in C++: by value, by pointer, and by reference.

How to call a function in C++? ›

A function can be declared by writing its return type, the name of the function, and the arguments inside brackets. It informs the compiler that this particular function is present. In C++, if you want to define the function after the main function, then you have to declare that function first.

How many types of arguments are there in C++? ›

Moreover, C++ supports three types of argument data types – pass by value, pass by reference, and pass by pointer.

How to call main () with arguments in C? ›

The main() function has two arguments that traditionally are called argc and argv and return a signed integer. Most Unix environments expect programs to return 0 (zero) on success and -1 (negative one) on failure. The argument vector, argv, is a tokenized representation of the command line that invoked your program.

Can main method be void C++? ›

In C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return type of main is int, i.e. main() will return an integer value by default. In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error.

Is it possible to call a main () inside another main function in C++? ›

Yes, we can call the main() within the main() function. The process of calling a function by the function itself is known as Recursion. Well,you can call a main() within the main() function ,but you should have a condition that does not call the main() function to terminate the program.

How many parameters you can pass to main function? ›

The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.

Can we call main () function recursively? ›

In 'C', the "main" function is called by the operating system when the user runs the program and it is treated the same way as every function, it has a return type. Although you can call the main() function within itself and it is called recursion.

What are the 4 types of functions in C? ›

What are the different categories of functions in C Programming?
  • Functions without arguments and without return values.
  • Functions without arguments and with return values.
  • Functions with arguments and without return values.
  • Functions with arguments and with return values.
Mar 9, 2021

Why do we use int main () in C++? ›

int main represents that the function returns some integer even '0' at the end of the program execution. '0' represents the successful execution of a program.

What does main function return in C? ›

What should main() return in C/C++? The return value of main() function shows how the program exited. The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value.

What type is a command line argument in C? ›

What are Command Line Arguments in C? Command line arguments are nothing but simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.

How to check command line arguments in C? ›

C allows a program to obtain the command line arguments provided when the executable is called, using two optional parameters of "main()" named "argc (argument count)" and "argv (argument vector)". The "argc" variable gives the count of the number of command-line parameters provided to the program.

How do I create a command line argument? ›

A command line argument is simply anything we enter after the executable name, which in the above example is notepad.exe. So for example, if we launched Notepad using the command C:\Windows\System32\notepad.exe /s, then /s would be the command line argument we used.

What is the function of command line? ›

A command-line interface (CLI) is a text-based user interface (UI) used to run programs, manage computer files and interact with the computer. Command-line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces.

What does it mean to use a command line argument? ›

Command line arguments allow the user to affect the operation of an application. For example, an application might allow the user to specify verbose mode--that is, specify that the application display a lot of trace information--with the command line argument -verbose .

What is the use of command line arguments? ›

Command line arguments in C/C++

We can also give command-line arguments in C and C++. Command-line arguments are given after the name of the program in command-line shell of Operating Systems.

What are the main features of command line? ›

1.1 CLI Features
  • 1 Asset Discovery, Management, and Grouping. Table 1-1 shows the functions that the CLI can perform for asset discovery, management, and grouping. ...
  • 2 Operating System Provisioning and Patching. ...
  • 3 Firmware Provisioning. ...
  • 4 Administration.

What are 5 examples of command line operating systems? ›

Operating system command-line interfaces

Examples of command-line interpreters include DEC's DIGITAL Command Language (DCL) in OpenVMS and RSX-11, the various Unix shells (sh, ksh, csh, tcsh, zsh, Bash, etc.), CP/M's CCP, DOS' COMMAND.COM, as well as the OS/2 and the Windows CMD.

How to get command line argument in C? ›

C allows a program to obtain the command line arguments provided when the executable is called, using two optional parameters of "main()" named "argc (argument count)" and "argv (argument vector)". The "argc" variable gives the count of the number of command-line parameters provided to the program.

What is the first argument of command line in C? ›

argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL. For information on how to suppress command-line processing, see Customize C++ command-line processing. By convention, argv[0] is the filename of the program.

How do I run a command line argument? ›

A command line argument is simply anything we enter after the executable name, which in the above example is notepad.exe. So for example, if we launched Notepad using the command C:\Windows\System32\notepad.exe /s, then /s would be the command line argument we used.

What is argument in C with example? ›

These are also called Actual arguments or Actual Parameters. Example: Suppose a sum() function is needed to be called with two numbers to add. These two numbers are referred to as the arguments and are passed to the sum() when it called from somewhere else. C.

Videos

1. C++ Help - Input Arguments
(Monte Carlos)
2. C - Command line arguments and user keyboard input
(Multilingual Programming)
3. C++ Getting Input from Command Line Made Easy
(Code Morsels)
4. how to pass comand line argument inc and c++ program
(Jary Ullah)
5. C++ 13 - Arguments in functions Tutorial
(TheNewIkast)
6. Programming example: Passing arguments to a program
(Zyante ProgInCpp)

References

Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated: 22/07/2023

Views: 6164

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.