C / C ++中的默认int main参数 [英] Default int main arguments in C/C++

查看:160
本文介绍了C / C ++中的默认int main参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用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;
}

C

#include <stdio.h>

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

所以我一直想知道这是什么,参数在C / C ++在int main?我知道应用程序仍然会编译没有他们,但他们服务的目的是什么?

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?

推荐答案

它们保存在命令行上传递给程序的参数。例如,如果我有程序 a.out ,然后调用它:

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 

argv 将是一个包含


  1. [0] - 可执行文件的文件名始终是第一个元素

  2. [1] arg1参数

  3. [2] arg2 - 我已通过

  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 包含 argv 中的元素数量(如C中所示,

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:

#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;
}

这篇关于C / C ++中的默认int main参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆