-2

这就是我得到错误的地方,也是主要的,它给了我一个关于这个凹凸函数的隐式声明的警告。也不知道为什么。编辑:我刚刚了解到 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;
}
4

2 回答 2

1

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

如果声明器包含标识符列表,则声明列表中的每个声明应至少有一个声明器,这些声明器应仅声明标识符列表中的标识符,并且应声明标识符列表中的每个标识符。声明为 typedef 名称的标识符不应重新声明为参数。声明列表中的声明应不包含除寄存器以外的存储类说明符,也不包含初始化。

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

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

  • 看起来您需要传递 a char *,而不是 a char **(检查数据类型)
  • The attempted operation is to modify a string literal. Even if you correct the first issue, you'll essentially invoke undefined behavior. You need to pass a modifiable memory, like, an array.
于 2018-01-30T06:11:51.710 回答
0

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

Not really. See Sourav Gosh's answer (which gives useful advice). What you could do is define a different function (with another, unique, name), e.g.

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

and you could even define that function as static inline in some header file.

You might also use a macro:

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

but that is generally poor taste.

Notice that C and C++ are different languages. The code you show us is not correct C (see n1570).

I recommend to compile your code with all warnings and debug info (e.g. gcc -Wall -Wextra -g with GCC), and to use a debugger (e.g. gdb)

于 2018-01-30T06:43:50.347 回答