2014-09-24 119 views
0

以下switch語句是否正確?我的意思是我可以在一個switch case語句中使用常量和字符文字嗎? 它在代碼中工作,但我從良好實踐的角度要求。C語言中的switch語句

switch(arg[1]) { 
    case '4': 
     printf("value is 4\n"); 
     break; 
    case '6': 
     printf("value is 6\n"); 
     break; 
    case 'M': 
     printf("value is M\n"); 
     break; 
    default: 
     break; 
} 
+0

胡佳'deafult'! – ouah 2014-09-24 18:45:07

+0

或者,你知道,'printf(「value is%c \ n」,arg [1])' – 2014-09-24 18:45:59

+2

單字符文字是一個數字,不像「非常短的字符串」。 – usr2564301 2014-09-24 18:46:08

回答

3

它可以在代碼,但我是從良好做法的角度問。

是的,它的優良使用char變量和常量在switch語句。這是很常見的,例如,to process command line argumentschar是一個整數類型,而switchchar一樣適用於任何其他整數類型。

+1

感謝這是我正在尋找。 – user1060517 2014-09-24 18:57:03