Shubham Chaurasia
Shubham Chaurasia

Reputation: 2622

data types and switch-case statement resolution

Consider below code(C language) which contains duplicate cases. 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.

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. Why it doesn't?

Upvotes: 2

Views: 309

Answers (3)

Niklas Lindskog
Niklas Lindskog

Reputation: 148

Took too long and posted 7 minutes too late :P...

My guess would be the following: A char variable cannot hold 'a' + 'b', this would cause overflow, i.e. undefined behavior. But 'a' + 'b' is promoted to an int, due to integer promotion rules. char d can never equal this value and the compiler removes these cases entirely. int d can be equal to both cases and the compiler issues the error.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

The reason for this behavior is the value of 'a'+'b' on your system, which is 195 on systems with ASCII encoding. This is above 127, the highest char value on systems with signed characters. Therefore, the compiler safely ignores both case labels.

Since value 195 is within the range for int, the compiler can no longer ignore it, so it must issue a duplicate case error.

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:

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.

Upvotes: 6

Siddhesh
Siddhesh

Reputation: 1173

Duplicate Case Error means you have defined two cases with the same value in the switch statement. 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. Single quotes are meant for characters, not strings.

Upvotes: 0

Related Questions