2013-04-28 36 views
0

我有gcc編譯器顯示const char問題的警告。警告:已棄用的字符串常量轉換爲'char *'

如何擺脫警告?

感謝, 邁克爾

char * str_convert(int op) { 
    /*returns the string corresponding to an operation opcode. Used for screen output.*/ 
    if(op == PLUS) { 
    return "plus"; 
    } 
    else if (op == MULT) { 
    return "mult"; 
    } 
    else if (op == SUBS) { 
    return "subs"; 
    } 
    else if (op == MOD) { 
    return "mod"; 
    } 
    else if (op == ABS) { 
    return "abs"; 
    } 
    else if (op == MAX) { 
    return "max"; 
    } 
    else if (op == MIN) { 
    return "min"; 
    } 
    else { 
    return NULL; 
    } 
} 
+1

將返回類型更改爲const char *?順便說一句:爲什麼不使用開關/外殼? – 2013-04-28 22:34:34

+0

你能提供一個例子嗎?我喜歡學習它應該是什麼樣的方式?謝謝。 – 2013-04-28 23:13:10

回答

2

我覺得修復程序添加到const返回類型(以防止修改內容)。 我也會改變如果級聯切換/案例,但這與問題無關。

const char * str_convert(int op) { 
    /*returns the string corresponding to an operation opcode. Used for screen output.*/ 
    switch (op) { 
    case ABS: return "abs"; 
    case MAX: return "max"; 
    case MIN: return "min"; 
    case MOD: return "mod"; 
    case MULT: return "mult"; 
    case PLUS: return "plus"; 
    case SUBS: return "subs"; 
    default: return NULL; 
    } 
} 
1

您也不妨考慮使用模板「運」值,因爲編譯器將取代它使用的switch語句執行,在運行時評估的跳錶,與調用在編譯時評估版本N個函數,取決於模板值。

template <int op> 
const char * str_convert(void) 
{ 
    /*returns the string corresponding to an operation opcode. Used for screen output.*/ 
    switch (op) 
    { 
     case ABS: return "abs"; 
     case MAX: return "max"; 
     case MIN: return "min"; 
     case MOD: return "mod"; 
     case MULT: return "mult"; 
     case PLUS: return "plus"; 
     case SUBS: return "subs"; 
     default: return NULL; 
    } 
} 
相關問題