c++ - main 函数可以有默认参数值吗?

标签 c++ arguments program-entry-point default-value

如何像用户定义的函数一样为 main 函数参数设置默认值?

最佳答案

好吧,标准没有说明禁止 main 使用默认参数并说你已经成功合并编译器以像这样同意你

#include <iostream>

const char *defaults[] = { "abc", "efg" };

int main(int argc = 2, const char **argv = defaults)
{
    std::cout << argc << std::endl;
}

Live example .它编译时没有错误或警告,但仍然没用;徒劳的实验它几乎总是会打印 1

每次调用程序时,例如,不带参数(或任何数量的参数),argc 都会设置为 1argv[0] 指向程序名称,所以这样做是没有意义的,即这些变量永远不会保持不变,因此拥有默认值毫无意义,因为默认值永远不会被使用。

因此这种事情通常是用局部变量来实现的。像这样

int main(int argc, char **argv)
{
    int const default_argc = 2;
    char* const default_args[] = { "abc", "efg" };
    if (argc == 1)   // no arguments were passed
    {
       // do things for no arguments

       // usually those variables are set here for a generic flow onwards
       argc = default_argc;
       argv = default_args;
    }
}

关于c++ - main 函数可以有默认参数值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22551791/

相关文章:

ruby - 在 Ruby 中打印缺少函数参数的名称

在 C 中编译和运行没有 main() 的程序

c++ - 返回简历 :Mat pointer to main function

c++ - 什么时候允许在 C++ 中调用 lua_gc 同时使用 lua_newuserdata

c++ - 为派生类实现内部运算符

c++ - 与兄弟类型之间的侧向转换是否保留 C++ 中的地址?

c - 将指针的结构数组作为函数参数传递?

C# 单个参数的多个值

c++ - 类中的 int main

C中调用main函数