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

2020-06-30 05:39发布

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?

标签: c++ c
4条回答
Root(大扎)
2楼-- · 2020-06-30 06:08

Those are for command-line arguments. argc is the number of arguments, and the arguments are stored as an array of null-terminated strings (argv). Normally, a program with no command-line arguments passed in will still have one stored in argv; namely, the name used to execute the program (which won't always be there, depending on how the program is executed, but I can't remember what the circumstances are for that).

查看更多
男人必须洒脱
3楼-- · 2020-06-30 06:19

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;
}
查看更多
Bombasti
4楼-- · 2020-06-30 06:28

argc and argv are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv, this will usually be one more than the number of arguments you pass from terminal, as usually the first is the name of the program.

查看更多
We Are One
5楼-- · 2020-06-30 06:29

If you want to accept arguments through commandline ,then you need to use the arguments in the main function .argc is the argument count and array of charecter pointers list the arguments. refer this link http://www.cprogramming.com/tutorial/c/lesson14.html

查看更多
登录 后发表回答