导读:最近在联系《C程序设计语言》上的练习题,因为第二门语言学习的就是C,所以,看书起来也是“走马观花”,做到一个联系题时,需要进行条件多分枝判断,结果,卡在了switch的case语句处。这才认真看书,搞清楚了switch在PHP和C中的去别。
详细:
PHP,The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value
it equals to. This is exactly what the switch statement is for.
详见这里。
也就是说,case语句可以是 常量或简单的表达式。
而
C,switch语句是一种多路判定语句,他测试表达式是否与 一些常量整数值 中的某一个值匹配,并执行相应的分支动作。
试了,这里是 常量表达式, 而非常量或表达式。
这就是区别了。
<?php $strdate = 'Jun 4 2008 11:34PM'; $month = date('M', strtotime($strdate)); switch ($month) { case ($month=='Jan' || $month=='Feb' || $month=='Mar'): $quarter = "Q1 2008"; break; case ($month=='Apr' || $month=='May' || $month=='Jun'): $quarter = "Q2 2008"; break; case ($month=='Jul' || $month=='Aug' || $month=='Sep'): $quarter = "Q3 2008"; break; case ($month=='Oct' || $month=='Nov' || $month=='Dec'): $quarter = "Q4 2008"; break; } ?>
#include <stdio.h> int main() { int user_input; int ret; printf("Plz choose one number to input, 10, 20, 30:\n"); scanf("%d", &user_input); switch(user_input){ case 10: ret = user_input * 10; break; case 20: ret = user_input * 5; break; case 30: ret = user_input * 2; break; default: ret = user_input; break; } printf("%d", ret); }
好好看书,不能走马观花呀。