这就是我收到错误的地方,也是在主要部分,它向我发出了此凹凸函数隐式声明的警告。也不知道为什么。编辑:我刚刚了解到 C 不能有默认参数。有没有解决的办法?
void bump(char*s, char c = 'o')
{
s.push_back(c);
}
int main()
{
char *s = "foo";
printf("%s\n",s);
bump(&s, '\0');
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 。您需要传递可修改的内存,例如数组。
关于c - 在函数定义中提供默认参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514657/