c++ – What is the difference between a main with arguments and another without arguments in c ++?

Question:

There is a main that is like this.

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

}

And another that is simply like this:

int main(){

  }

So far I have used both and both have worked for me, so I have not identified what the difference is between using one or the other, or if they have different purposes.

Answer:

In the first main

  • argc: stores the amount (number) of parameters, counting on the executable name.

  • * argv []: An array containing all the received parameters 1 counting on the executable name.

if you are used to using the terminal many times you do things like this:

miPrograma argumento1 argumento2 

That is when through the first main but NOT the second, you can obtain those parameters and use them within your program to generate one behavior or another, check which parameter was passed to it, or the number of parameters that have been passed to it when executing its program ect.

you can compile this example:


int main(int argc, char *argv[])
{
    printf("numero de argumentos: %i\n", argc);

    printf("Argumento 0: %s\n", argv[0]);
    printf("Argumento 1: %s\n", argv[1]);
    printf("Argumento 2: %s\n", argv[2]);
    printf("Argumento 3: %s\n", argv[3]);
    return 0;
}

and run it like this for example:

a.out stack overflow es

Shell:

./a.out stack overflow es
numero de argumentos: 4
Argumento 0: ./a.out
Argumento 1: stack
Argumento 2: overflow
Argumento 3: es

(if your program is called a.out)


the following code uses this syntax char **argv instead of char *argv[] but "basically" it is the same. One is more of c and the other of c ++, some call it a two-dimensional array of characters and others an array of pointers to characters .

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("Argumento 0: %s\n", argv[0]);
    printf("Argumento 1: %s\n", argv[1]);
    printf("Argumento 2: %s\n", argv[2]);
    printf("Argumento 3: %s\n", argv[3]);
    return 0;
}

1 * argv []: array of character pointers.

Scroll to Top