【发布时间】:2012-02-05 07:15:39
【问题描述】:
在 C++ 中,在某些情况下我倾向于省略参数的名称。但是在 C 语言中,当我省略参数的名称时出现错误。
代码如下:
void foo(int); //forward-decl, it's OK to omit the parameter's name, in both C++ and C
int main()
{
foo(0);
return 0;
}
void foo(int) //definition in C, it cannot compile with gcc
{
printf("in foo\n");
}
void foo(int) //definition in C++, it can compile with g++
{
cout << "in foo" << endl;
}
这是为什么呢? C函数定义中不能省略参数名吗?
【问题讨论】:
-
编写多语言源文件是(非常)艰苦的工作。我建议您仅使用一种语言保存每个源文件。
-
但是,如果您确实想要在 C 和 C++ 中编译某些东西,则无需编写单独的函数来使用
printf和str::cout。printf适用于两种语言。我建议不要使用可以写成一个的两个函数,因为它们的功能可能不相同。 -
如果原因是-Wunused-parameter,有更好的解决方案:stackoverflow.com/a/3599170/1904815。
-
在这种情况下,在内存中创建了一个 int 空间,我们无法访问它或者二进制简单地忽略参数?如果我们用一些 int 作为参数调用函数,内存中的空间会被保留吗?
标签: c++ c compilation