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

  • Article

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.

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.

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.

  • 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.

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

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

FAQs

What is the main function with command line arguments in C? ›

The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters. We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Operating Systems.

How to pass arguments to main function in C++? ›

They are provided in the command-line shell of operating systems with the program execution command. But to pass command-line arguments, we typically define main() with two arguments, where the first argument is the number of command-line arguments and the second is the list of command-line arguments.

How to run command line arguments in C++? ›

To create a command line argument, simply pass a value or parameter after the program name when executing a program in the command line or terminal. The program can then retrieve and use these values as arguments during its execution.

How to pass command line arguments to main method? ›

Use the syntax: “java YourProgramClassName arg1 arg2 arg3” to pass command-line arguments. Replace “arg1, arg2,...” with the real arguments and “YourProgramClassName” with the name of your class.

What is an example of 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 main() function in C? ›

The main function in C programming is a special type of function that serves as the entry point of the program where the execution begins. By default, the return type of the main function is int. There can be two types of main() functions: with and without parameters.

How to write main function in C++? ›

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( void ); int main( int argc, char *argv[ ] ); int main( int argc, char *argv[ ], char *envp[ ] );

How many arguments can be passed to a function in C++? ›

Answer 1: When it comes to passing arguments to function, the maximum number of arguments that is possible to pass is 253 for a single function of the C++ programming language. Furthermore, the separation of arguments takes place by commas.

How to pass function arguments in C? ›

Passing arguments by value

When an argument is passed by value, the C function receives a copy of the actual value of the argument. To specify that the argument should always be passed by value, use the keyword ByVal preceding the parameter declaration for that argument in the Declare statement for the C function.

What is an argument in C with an 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.

Does every C++ program need a main function? ›

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.)

How do I give a command line argument in command prompt? ›

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 passing command line arguments? ›

passing command line arguments to bash scripts. A command line argument is a parameter that we can supply to our Bash script at execution. They allow a user to dynamically affect the actions your script will perform or the output it will generate.

How is main declared for command line argument? ›

The declaration of main looks like this: int main(int argc, char *argv[]); This indicates that main is a function returning an integer. In hosted environments such as DOS or UNIX, this value or exit status is passed back to the command line interpreter.

Which is the correct form to declare main with command line arguments? ›

Command-line Arguments: main( int argc, char *argv[] )

Here argc means argument count and argument vector.

What is function with argument in C? ›

The values that are declared within a function when the function is called are known as an argument. The variables that are defined when the function is declared are known as parameters. 2. These are used in function call statements to send value from the calling function to the receiving function.

What are command line arguments using function? ›

To facilitate the main() function to accept arguments from the command line, you should define two arguments in the main() function – argc and argv[]. argc refers to the number of arguments passed and argv[] is a pointer array that points to each argument passed to the program.

What is int argc and char * argv in C? ›

main is the first function called in any C program. int argc is a parameter that tells you how many parameters are in the array argv. char ** argv (aka char * argv[]) is an array of pointers to strings (aka char *) which are the preparsed parameters given on the command line. argv[0] is the name of the program.

What is the main function prototype in C? ›

A Function Prototype

In C, all functions must be written to return a specific TYPE of information and to take in specific types of data (parameters). This information is communicated to the compiler via a function prototype. The function prototype is also used at the beginning of the code for the function.

Top Articles
Data Science Examples (See 8 Real Applications) - Addepto
Why Can't I Be Happy Even When Life Is Going Great?
Dunhams Treestands
Diario Las Americas Rentas Hialeah
Edina Omni Portal
Rubratings Tampa
Walgreens Pharmqcy
Noaa Swell Forecast
Puretalkusa.com/Amac
Nikki Catsouras Head Cut In Half
Music Archives | Hotel Grand Bach - Hotel GrandBach
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Helloid Worthington Login
Ukraine-Russia war: Latest updates
Cnnfn.com Markets
Rainfall Map Oklahoma
Craigslist Malone New York
Bcbs Prefix List Phone Numbers
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
111 Cubic Inch To Cc
24 Hour Drive Thru Car Wash Near Me
Walmart Car Department Phone Number
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Scream Queens Parents Guide
Employee Health Upmc
Mybiglots Net Associates
Slim Thug’s Wealth and Wellness: A Journey Beyond Music
Hdmovie2 Sbs
Cpt 90677 Reimbursem*nt 2023
Craig Woolard Net Worth
Ltg Speech Copy Paste
Water Temperature Robert Moses
Dal Tadka Recipe - Punjabi Dhaba Style
Jesus Calling Feb 13
R3Vlimited Forum
CARLY Thank You Notes
Flashscore.com Live Football Scores Livescore
Afspraak inzien
Page 5662 – Christianity Today
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
2700 Yen To Usd
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Amc.santa Anita
Tricare Dermatologists Near Me
Bmp 202 Blue Round Pill
Crystal Glassware Ebay
What Does the Death Card Mean in Tarot?
Mawal Gameroom Download
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Www Extramovies Com
Www.card-Data.com/Comerica Prepaid Balance
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 5531

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.