2015-02-07 27 views
0
發生突變

說我有這個功能:檢查字符串可以在C

void f(char *s) { 
    s[0] = 'x'; 
} 

這個功能有時會導致錯誤,有時沒有。例如,

char *s = "test"; 
f(s); // Error 

char t[] = "test"; 
f(t); // Success 

內部功能f,是有可能確定s[0] = 'x';是否會在這樣做之前造成的錯誤?

+5

我不相信有任何便攜的方式來做到這一點。不過,可能會有一些特定於平臺的技術。 – templatetypedef 2015-02-07 00:58:04

+0

如果有人選擇以表現未定義行爲的方式使用您的功能,並且您的功能已經完整記錄,那就對他們了。 – 2015-02-07 01:00:02

+0

試圖修改'const'對象導致未定義的行爲。實際上,這意味着你不能寫一個測試它的函數。但是,您可以通過嚴格指定哪些對象是'const'來進行編譯時診斷,因此您絕不會試圖修改它們或將'const'對象傳遞給修改它的函數。 – EOF 2015-02-07 01:30:36

回答

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'ness程。除極少數情況外,兩者都是一個問題的積極指標。

注意:這是語言中的一個異常,可以在沒有const限定符的情況下聲明s。在需要時使用const的練習(例如,當使用字符串文字初始化指針時)。很多程序錯誤都以這種方式消除。

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'; 
} 
+2

「......記錄函數是否需要其參數是可變的......」是不是發明了「const」? – 2015-02-07 02:10:49

+0

@ c-smile在這個例子中,函數'g'需要參數's'是非常量的。在這方面有沒有辦法使用'const'?如果是這樣,請發表一個答案,我會接受它。 – dln385 2015-02-07 03:25:34

+2

您的函數'g()'修改傳遞給它的字符串的事實是您需要的所有文檔,在這裏。 – 2015-02-07 03:46:57