Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default int main arguments in C/C++ [duplicate]

Tags:

c++

c

I was messing around with projects in C/C++ and I noticed this:

C++

#include <iostream.h>

int main (int argc, const char * argv[]) {
    // insert code here...
    cout << "Hello, World!\n";
    return 0;
}

and

C

#include <stdio.h>

int main (int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    return 0;
}

So I've always sort of wondered about this, what exactly do those default arguments do in C/C++ under int main? I know that the application will still compile without them, but what purpose do they serve?

like image 997
learner Avatar asked Sep 13 '25 09:09

learner


1 Answers

They hold the arguments passed to the program on the command line. For example, if I have program a.out and I invoke it thusly:

$ ./a.out arg1 arg2 

The contents of argv will be an array of strings containing

  1. [0] "a.out" - The executable's file name is always the first element
  2. [1] "arg1" - The other arguments
  3. [2] "arg2" - that I passed

argc holds the number of elements in argv (as in C you need another variable to know how many elements there are in an array, when passed to a function).

You can try it yourself with this simple program:


C++

#include <iostream>

int main(int argc, char * argv[]){
    int i;
    for(i = 0; i < argc; i++){
        std::cout << "Argument "<< i << " = " << argv[i] << std::endl;
    }
    return 0;
}

C

#include <stdio.h>

int main(int argc, char ** argv){
    int i;
    for(i = 0; i < argc; i++){
        printf("Argument %i = %s\n", i, argv[i]);
    }
    return 0;
}
like image 98
Kninnug Avatar answered Sep 16 '25 00:09

Kninnug