简体   繁体   English

数据类型和switch-case语句解析

[英]data types and switch-case statement resolution

Consider below code(C language) which contains duplicate cases. 考虑下面包含重复案例的代码(C语言)。 Compiler does not give any warning/error this time. 编译器这次没有给出任何警告/错误。

void testSwitchCase() {
char d = 0;
switch(d) {
  case 'a' + 'b':
       printf("I am case 'a' + 'b'\n");
       break;
  case 'a' + 'b':
       printf("I am case 'a' + 'b' \n");
       break;
    }
}

But if I change char d = 0 to int d = 0 , compiler starts raising an error regarding duplicate cases. 但是如果我将 char d = 0 更改int d = 0 ,编译器会开始引发有关重复个案的错误。

error: duplicate case value 错误:重复案例值

I understand that the expression 'a' + 'b' should evaluate to an int but my point is that it should raise duplicate case error both the times. 我理解表达式'a' + 'b'应该计算为int但我的观点是它应该同时引发重复的大小写错误。 Why it doesn't? 为什么不呢?

The reason for this behavior is the value of 'a'+'b' on your system, which is 195 on systems with ASCII encoding. 这种行为的原因是系统上'a'+'b'的值,在具有ASCII编码的系统上为195。 This is above 127, the highest char value on systems with signed characters. 这大于127,是带有签名字符的系统上的最高char值。 Therefore, the compiler safely ignores both case labels. 因此,编译器安全地忽略两个case标签。

Since value 195 is within the range for int , the compiler can no longer ignore it, so it must issue a duplicate case error. 由于值195int的范围内,编译器不能再忽略它,因此它必须发出重复的大小写错误。

If you change 'a'+'b' to '0'+'1' , you get 97 , which is within the range of a signed char, you get duplicate case error with char d as well: 如果你将'a'+'b'改为'0'+'1' ,你得到97 ,这是在一个有符号的字符的范围内,你得到重复的案例错误与char d

char d = 0;
switch(d) {
case '0' + '1':
   printf("I am case 'a' + 'b'\n");
   break;
case '0' + '1':
   printf("I am case 'a' + 'b' \n");
   break;
}

Demo. 演示。

Took too long and posted 7 minutes too late :P... 花了太长时间,太晚发布了7分钟:P ......

My guess would be the following: A char variable cannot hold 'a' + 'b', this would cause overflow, ie undefined behavior. 我的猜测如下:char变量不能保持'a'+'b',这会导致溢出,即未定义的行为。 But 'a' + 'b' is promoted to an int, due to integer promotion rules. 但是由于整数提升规则,'a'+'b'被提升为int。 char d can never equal this value and the compiler removes these cases entirely. char d永远不能等于这个值,编译器会完全删除这些情况。 int d can be equal to both cases and the compiler issues the error. int d可以等于两种情况,编译器发出错误。

Duplicate Case Error means you have defined two cases with the same value in the switch statement. 重复案例错误意味着您已在switch语句中定义了两个具有相同值的案例。 You are probably looking at your code thinking "but they are all different." 你可能正在考虑你的代码思考“但它们都是不同的。” To you they are different. 对你而言,他们是不同的。 To the compiler they look much different. 对于编译器,它们看起来大不相同。

You have defined case statements using the character notation. 您已使用字符表示法定义了case语句。 Single quotes are meant for characters, not strings. 单引号用于字符,而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM