switch case...

Could you give a right syntax for switch case clause!

Switch (variable){

 case value:
.
.
.
?

Thanks in advance!
majalaAsked:
Who is Participating?
 
abdijConnect With a Mentor Commented:
Hi,
 It is like this:

 switch(expression)
 {
  case Value_1:
              [break;]
  case Value_n:
              [break;]
 }

 the expression may be simple or compound.

For example
 char cChar = 'z';

// simple
 switch(cChar)
 {
  case 'a':
     printf("Char is a");
     break;
  .
  .
  case 'z':
     printf("Char is z");
     break;
 }

 or

// compound
 switch(cChar - '0')
 {
  case 'a':
     printf("Char is a");
     break;
  .
  .
  case 'z':
     printf("Char is z");
     break;
 }

The Expression must return a value (here char worked because internally char is ascii value.

Hope this is not an assignment and you are just a C beginner.

Bye
Abdij
0
 
940961slCommented:
switch (variable)
{
   case value1 :
   case value2 :
      //do some stuff if the value is 1 or 2
   break;
   case value3 :
      //do some stuff if the value is 3
   break;
   default :
     //do some stuff if the value is not 1, 2 or 3
   break;
}

the variable is compared with the case values from the top to the bottom, and stops at a break. You can play a little bit with the break, eg :

switch (value)
{
   case value1 :
      DoStatement1();
   case value2 :
      DoStatement2();
   break;
   case value3 :
      DoStatement3();
   break;
}

in this example, if the value is 1, the switch will execute statement 1 AND 2, because of the break missing after statement 1. For a value 2, only statement 2 is executed, and for a value 3, only statement 3. Other values are ingnored.

WARNING : the values can't be strings. if you want to compare strings, you have to use strcmp();

}
0
All Courses

From novice to tech pro — start learning today.