说我有这个功能:
void f(char *s) {
s[0] = 'x';
}
此功能有时会导致错误,有时不会导致错误。例如,
char *s = "test";
f(s); // Error
char t[] = "test";
f(t); // Success
内部函数f
,是否可以在执行此操作之前确定s[0] = 'x';
是否会导致错误?
答案 0 :(得分:2)
调用者有责任遵守参数可更改的功能要求,而不是相反。
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,或者去除const'ness。除极少数情况外,两者都是问题的积极指标。
注意:语言中的异常可以在没有const限定符的情况下声明。在需要的地方练习使用const(例如,在使用字符串文字初始化指针时)。这样就消除了很多程序错误。
答案 1 :(得分:0)
鉴于我收到的反馈,听起来我应该记录该函数是否要求其参数是可变的。例如:
#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';
}