在函数定义中提供默认参数值

Providing default argument value in function definition

这就是我遇到错误的地方,主要也是,它给我警告这个碰撞函数的隐式声明。也不知道为什么。编辑:我刚刚了解到 C 不能有默认参数。有没有解决的办法?

void bump(char*s, char c = 'o')
 {
   s.push_back(c);
 }

int main()
{
 char *s = "foo";
 printf("%s\n",s);

 bump(&s, '[=10=]'); 
 printf("%s\n",s);

 bump(&s, 'x');
 printf("%s\n",s);

 return 0;
}

首先,C 中没有默认参数。引用 C11,章节 §6.9.1/P6,函数定义强调我的)

If the declarator includes an identifier list, each declaration in the declaration list shall have at least one declarator, those declarators shall declare only identifiers from the identifier list, and every identifier in the identifier list shall be declared. An identifier declared as a typedef name shall not be redeclared as a parameter. The declarations in the declaration list shall contain no storage-class specifier other than register and no initializations.

所以,你的函数定义是一个语法错误。编译器也在抱怨同样的事情。

也就是说,在 bump() 函数调用中,

  • 看起来您需要传递 char *,而不是 char **(检查数据类型)
  • 尝试的操作是修改字符串文字。即使您更正了第一个问题,您实际上也会调用 undefined behavior。你需要传递一个可修改的内存,比如一个数组。

I just learned that C cannot have default arguments. Is there a way around this?

不是真的。请参阅 (其中提供了有用的建议)。你可以做的是定义一个 different 函数(使用 another, unique, name),例如

void bump_o(char*s) { bump(s, 'o'); }

您甚至可以在某些头文件中将该函数定义为 static inline

您还可以使用宏:

#define BUMP_O(S) bump((S), 'o')

但这通常是品味不佳。

请注意 C 和 C++ 是不同的语言。您向我们展示的代码不是正确的 C(参见 n1570)。

我建议使用所有警告和调试信息编译您的代码(例如 gcc -Wall -Wextra -gGCC), and to use a debugger (e.g. gdb