• C

switch case...

Could you give a right syntax for switch case clause!

Switch (variable){

 case value:
.
.
.
?

Thanks in advance!
majalaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
abdijCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.