104

Possible Duplicates:
What are the arguments to main() for?
What does int argc, char *argv[] mean?

Every program is starting with the main(int argc, char *argv[]) definition.

I don't understand what it means. I would be very glad if somebody could explain why we use these arguments if we don't use them in the program? Why not just: int main()?

Is the name of the program one of the elements of *argv[] and argc is the count of the number of arguments in *argv[]? What are the other arguments sent to *argv[]? How do we send them?

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
  • 1
    Note that if you don't intend to use command line arguments, it is perfectly permissible (and very sensible) to define the function `int main(void)` or `int main()`. The return type (`int`) is mandatory in C99 or C11; compilers sometimes let you omit it still if you don't specify which version of the C standard your code adheres to. See also [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/). – Jonathan Leffler Feb 05 '16 at 03:29

8 Answers8

131

The arguments argc and argv of main is used as a way to send arguments to a program, the possibly most familiar way is to use the good ol' terminal where a user could type cat file. Here the word cat is a program that takes a file and outputs it to standard output (stdout).

The program receives the number of arguments in argc and the vector of arguments in argv, in the above the argument count would be two (The program name counts as the first argument) and the argument vector would contain [cat,file,null]. While the last element being a null-pointer.

Commonly, you would write it like this:

int  // Specifies that type of variable the function returns.
     // main() must return an integer
main ( int argc, char **argv ) {
     // code
     return 0; // Indicates that everything went well.
}

If your program does not require any arguments, it is equally valid to write a main-function in the following fashion:

int main() {
  // code
  return 0; // Zero indicates success, while any 
  // Non-Zero value indicates a failure/error
}

In the early versions of the C language, there was no int before main as this was implied. Today, this is considered to be an error.

On POSIX-compliant systems (and Windows), there exists the possibility to use a third parameter char **envp which contains a vector of the programs environment variables. Further variations of the argument list of the main function exists, but I will not detail it here since it is non-standard.

Also, the naming of the variables is a convention and has no actual meaning. It is always a good idea to adhere to this so that you do not confuse others, but it would be equally valid to define main as

int main(int c, char **v, char **e) {
   // code
   return 0;
}

And for your second question, there are several ways to send arguments to a program. I would recommend you to look at the exec*()family of functions which is POSIX-standard, but it is probably easier to just use system("command arg1 arg2"), but the use of system() is usually frowned upon as it is not guaranteed to work on every system. I have not tested it myself; but if there is no bash,zsh, or other shell installed on a *NIX-system, system() will fail.

starball
  • 20,030
  • 7
  • 43
  • 238
Frank
  • 2,640
  • 2
  • 21
  • 21
  • If I'm not wrong than the minimum possible value of `argc` is 1 and `argv[0]` holds the string `./mymainprogram` whereas `argv[1]` is `NULL`. My questions are- **1:** What is the maximum value that `argc` can hold? **2:** What are these strings that are added to the `argv[]`? – phougatv Jan 22 '15 at 06:21
  • 1
    @barnes - The maximum is OS dependent. In Win32 the command line itself has a length limit of 32K, so `argc` has a practical limit of 16K. – Jesse Chisholm Feb 10 '16 at 14:26
  • 1
    @barnes: Old DOS is limited to 127 bytes for command line arguments, not that it matters much anymore but just a fun fact that I happen to remember ^_^ – Frank Feb 24 '18 at 09:31
  • @JesseChisholm I realise this is quite old now, but it's worth saying that that limit *doesn't* apply for Cygwin processes that start other Cygwin processes (they pass argv directly in such cases). Also, I've been working on [a way to bypass the Windows limit](https://github.com/al45tair/ArgX). – al45tair Jan 12 '20 at 09:05
  • @alastair Agreed, programmatic starting of a process has essentially no limits, whereas typing in the command at the shell does. It is the COMMAND shell on DOS that Frank refers to that limited it to 127 bytes, not the receiving program. Likewise the effective 16K in Win32's CMD shell. – Jesse Chisholm Jan 18 '20 at 21:29
  • @JesseChisholm The 32K limit is actually built into Windows itself, sadly. The CMD shell is even more limited (8K command line length, total). – al45tair Jan 19 '20 at 23:21
  • 1
    `char **envp` as a third argument is not part of the POSIX standard. See this [thread](https://stackoverflow.com/questions/10321435/is-char-envp-as-a-third-argument-to-main-portable) – ben Mar 17 '21 at 14:08
71

Those are for passing arguments to your program, for example from command line, when a program is invoked

$ gcc mysort.c -o mysort

$ mysort 2 8 9 1 4 5

Above, the program mysort is executed with some command line parameters. Inside main( int argc, char * argv[]), this would result in

Argument Count, argc = 7 

since there are 7 arguments (counting the program), and

Argument Vector, argv[] = { "mysort", "2", "8", "9", "1", "4", "5" };

Following is a complete example.

$ cat mysort.c
#include <stdio.h>
int main( int argc, char * argv [] ) {
    printf( "argc = %d\n", argc );
    for( int i = 0; i < argc; ++i ) {
        printf( "argv[ %d ] = %s\n", i, argv[ i ] );
    }
}

$ gcc mysort.c -o mysort

$ ./mysort 2 8 9 1 4 5
argc = 7
argv[ 0 ] = ./mysort
argv[ 1 ] = 2
argv[ 2 ] = 8
argv[ 3 ] = 9
argv[ 4 ] = 1
argv[ 5 ] = 4
argv[ 6 ] = 5

[The char strings "2", "8" etc. can be converted to number using some character to number conversion function, e.g. atol() (link)]

Arun
  • 19,750
  • 10
  • 51
  • 60
16

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • What does the name of the program have to do with the arguments passed to main()? –  Oct 09 '10 at 22:00
  • 1
    @Potatoswatter, @You, I updated my answer to explicitly say that envp isn't standard. @fahad, usually the first argument is the name of the application, this way you can know how your application has been called. – Colin Hebert Oct 09 '10 at 22:05
  • Just by its name,how would you know how it has been called? –  Oct 09 '10 at 22:07
  • @fahad, I meant "how the application had been named". This could for example be used to print an error message such as "Illegal option... usage: applicationName [-v]" – Colin Hebert Oct 09 '10 at 22:12
  • In *nix OSes it is not impossible for different "programs" to be symbolic links to the same executable file - knowing how it was invoked enables that executable to behave differently depending on what it was called as. A _classic_ example of this is I think the [busybox](https://en.wikipedia.org/wiki/BusyBox) utility - the same file behaves like literally hundreds of other utilities (perhaps in a "cut-down" or only implementing the most often used functionality of each) as just one executable which is advantageous in many scenarios... – SlySven Sep 11 '16 at 15:42
3

argc means the number of argument that are passed to the program. char* argv[] are the passed arguments. argv[0] is always the program name itself. I'm not a 100% sure, but I think int main() is valid in C/C++.

kraftan
  • 6,272
  • 2
  • 22
  • 24
  • `int main()` is valid in C++ only. In C you need to put a void like so: `int main(void)`. The C-style `int main(void)` is also valid in C++ although its usage in C++ is discouraged. – Ultimater Mar 07 '16 at 07:18
  • @Ultimater I'm pretty sure `int main()` is also valid in C. It declares a varargs function. – Navin Jul 04 '16 at 05:56
  • @Navin Many C++ compilers are very forgiving when they encounter C code since C++ allows both `int main()` and `int main(void)` to compile, but a C compiler, definitely an older C compiler, wouldn't support the C++ style `int main()`. I took a course on C/C++ that put a strong emphasis on portability, and if your assignment was supposed to be written in C and you gave it a `int main()` declaration, his assignment checker would complain, not even compiling it, and we'd lose points on the assignment unless we resubmitted it by the deadline. – Ultimater Jul 04 '16 at 06:16
1

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

int main(void) {
    /* ... */ 
}

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

You
  • 22,800
  • 3
  • 51
  • 64
  • Technically, `int main()` is a function taking arbitrarily many arguments, while `int main(void)` takes exactly zero arguments, so the latter is more correct. – You Oct 09 '10 at 22:45
  • 2
    no, in a *definition*, `int main()` is a function taking no parameters. In a *declaration* which is not a definition, it's a function taking unspecified parameters. This is 6.7.5.3/14 in n1256, or 6.5.5.3/10 in n794. The questioner is asking about a definition. – Steve Jessop Oct 09 '10 at 23:19
1

The comp.lang.c FAQ deals with the question

"What's the correct declaration of main()?"
in Question 11.12a.
cschol
  • 12,799
  • 11
  • 66
  • 80
  • 2
    ...but this isn't comp.lang.c, it's StackOverflow, a community where we *help* people by *answering* their questions, not redirecting them to manuals, FAQs, or lmgtfy links. – Mark Elliot Oct 09 '10 at 22:19
  • 1
    The question was already answered above. The C FAQ, however is still worth reading, imho. But it states in its license that it cannot be reproduced without permission. Therefore the links. Just for completeness sake. – cschol Oct 09 '10 at 22:29
0

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

You can run your application with parameters such as app -something -somethingelse. int argc represents number of these parameters and char *argv[] is an array with actual parameters being passed into your application. This way you can work with them inside of your application.

Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126