Friday, July 12, 2013

Switch case with char in C

We know that switch case statement works only with integer values. But what happens when we use char values?Does it return any error? Does it works?

To answer your questions, here is a program, which takes the char input and performs the switch case operation. Check out the below example and you will understand what happens.

Example:

  1. #include<stdio.h>
  2. main()
  3. {
  4. char var='a';
  5. switch(var)
  6. {
  7. case 'a':printf("Hello this is alphabet");
  8.             break;
  9. case 97: printf("Hello this is a number");
  10.              break
  11. default: printf("It is not default");
  12. }
  13. return 0;
  14. }
Check for the output of the above program. It gives an "ERROR". And the error shows as duplicate case. But actually written two different cases. This happens because, the char is evaluated to an integer value i.e.,  it ASCII value. The ASCII value of 'a' is 97. Hence it takes that value and returns and error.

This is what happens when we take a char into a switch case. 

Do you know that we can also perform a switch case operation even with a floating-type data. To know click here.