switch语句
#include <stdio.h>
void main()
{
const int two = 2;
int me = 2;
switch(me){
case 1:
printf("1");
break;
case two: //be different in c and c++
printf("TWO");
break;
default:
printf("default");
break;
}
}
void main()
{
const int two = 2;
int me = 2;
switch(me){
case 1:
printf("1");
break;
case two: //be different in c and c++
printf("TWO");
break;
default:
printf("default");
break;
}
}
上述同样的代码,若保存为switch.cpp编译,没有问题。要保存为switch.c编译,则在vc里面提示:error C2051: case expression not constant。
这个switch语句展示了,在C语言中,const其实并不是“真正的常量”。
再看这样一段代码:
#include <stdio.h>
void main()
{
const int two = 2;
int me = 3;
switch(me){
case 1:
printf("1");
break;
default:
printf("default\n");
//break;
case two:
printf("TWO\n");
break;
}
}
void main()
{
const int two = 2;
int me = 3;
switch(me){
case 1:
printf("1");
break;
default:
printf("default\n");
//break;
case two:
printf("TWO\n");
break;
}
}
程序输出的结果:
default
TWO