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

标签 c 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, '\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/

相关文章:

c - 我很难理解这段代码

比较数组中的三个数字

c - 鉴别 "bit stuffing"之后的位

c++ - 如何将指针传递给函数并在函数 C++ 中动态分配内存

c++ - 在函数定义中使用 Eigen 库时,小数点未按预期存储

arrays - 使用指针交换数组

scala - 定义翻转参数的函数

c - 如果 C 语言中 opendir() 之后没有执行 closedir() 会怎样?

c - 如何在 C 中使用 try-catch(或 C 中的等效项)

c - 反转打印功能