说我有这个功能:检查字符串可以在C
void f(char *s) {
s[0] = 'x';
}
这个功能有时会导致错误,有时没有。例如,
char *s = "test";
f(s); // Error
char t[] = "test";
f(t); // Success
内部功能f
,是有可能确定s[0] = 'x';
是否会在这样做之前造成的错误?
说我有这个功能:检查字符串可以在C
void f(char *s) {
s[0] = 'x';
}
这个功能有时会导致错误,有时没有。例如,
char *s = "test";
f(s); // Error
char t[] = "test";
f(t); // Success
内部功能f
,是有可能确定s[0] = 'x';
是否会在这样做之前造成的错误?
责任是在调用者遵守函数的要求,可以改变参数,而不是相反。
const char *s = "test"; // tell compiler s is immutable
f(s); // compilation error since f() requires a non-const argument
char t[] = "test";
f(t); // Success
从在上述拒绝F(S)停止编译器的唯一方法是要么从s的声明删除常量,或铸const'ness程。除极少数情况外,两者都是一个问题的积极指标。
注意:这是语言中的一个异常,可以在没有const限定符的情况下声明s。在需要时使用const的练习(例如,当使用字符串文字初始化指针时)。很多程序错误都以这种方式消除。
鉴于我收到的反馈,它听起来像我应该反而记录函数是否需要它的参数是可变的。例如:
#include <stdio.h>
#include <string.h>
char* f(char*);
void g(char*);
int main(int argc, char *argv[]) {
// s is immutable.
char *s = "test";
puts(f(s));
// t is mutable.
char t[] = "test";
g(t);
puts(t);
}
/*
* Returns a copy of the given string where the first character is replaced with 'x'.
* Parameter s must contain at least one character.
*/
char* f(char *s) {
char *t = strdup(s);
t[0] = 'x';
return t;
}
/*
* Replaces the first character of the given sting with 'x'.
* Parameter s must contain at least one character and be mutable.
*/
void g(char *s) {
s[0] = 'x';
}
“......记录函数是否需要其参数是可变的......”是不是发明了“const”? – 2015-02-07 02:10:49
@ c-smile在这个例子中,函数'g'需要参数's'是非常量的。在这方面有没有办法使用'const'?如果是这样,请发表一个答案,我会接受它。 – dln385 2015-02-07 03:25:34
您的函数'g()'修改传递给它的字符串的事实是您需要的所有文档,在这里。 – 2015-02-07 03:46:57
我不相信有任何便携的方式来做到这一点。不过,可能会有一些特定于平台的技术。 – templatetypedef 2015-02-07 00:58:04
如果有人选择以表现未定义行为的方式使用您的功能,并且您的功能已经完整记录,那就对他们了。 – 2015-02-07 01:00:02
试图修改'const'对象导致未定义的行为。实际上,这意味着你不能写一个测试它的函数。但是,您可以通过严格指定哪些对象是'const'来进行编译时诊断,因此您绝不会试图修改它们或将'const'对象传递给修改它的函数。 – EOF 2015-02-07 01:30:36