C language > Beginner questions

switch case

(1/1)

ahsjar:
hello,
shouldn't this work?


--- Code: ---switch (x)
{
    case a:
    case b:
    case c:
         ...;
         break;
    case d:
         ...;
         break;
    case e:
         ...;
         break;
}
--- End code ---

but i am getting the following error (for lines at "case b:" and "case c:")
error #2001: Syntax error: found ':' - expecting ';'.
error #2061: Illegal statement termination.


ahsjar

frankie:
In the switch statement the cases must be constant integers.
In your code a, b, c, etc are constant integers?
The use of multiple cases with the same body is perfectly legal.

ahsjar:
thanks for the quick reply..

yes, they are constant integers and i tested it - in the same code this works:

switch (x)
{
    case a:
         ...;
         break;
    case b:
         ...;
         break;
    case c:
         ...;
         break;
}
 
and this doesn't:

switch (x)
{
    case a:
    case b:
    case c:
         ...;
         break;
}

hmm... i wonder what it is?  ???

frankie:
This sample:

--- Code: --- int a,b,c,d, x;

x='a';
a=b=c=d='x';

switch(x)
{
case 'a':
case 'x':
case 'z':
case 'f':
case 'j':
case 'w':
case 'y':
a=b;
break;
case 'b':
b=c;
break;
case 'c':
c=d;
break;
case 'd':
d=a;
break;
}
printf("%d%d%d%d%d", a, b, c, d, x);

switch(x)
{
case 'a':
case 'b':
case 'c':
case 'd':
d=a;
break;
}

--- End code ---
Works without problems here.
What really are a, b, c etc?
This snippet gives a similiar error:

--- Code: --- #define d 'd':

switch(x)
{
case 'a':
case 'b':
case 'c':
case d:
c=a;
break;
}

--- End code ---
Could you post a snippet of your code, possibly a simple project with the options you have set.

ahsjar:
hey Frankie!
sorry i took your time... the problem was that i was staring at the screen so long that i just didn't see that i wrote:

case a:
       b:
       c:
       ...;
       break;

but this looks interesting:


--- Code: --- #define d 'd':

switch(x)
{
case 'a':
case 'b':
case 'c':
case d:
c=a;
break;
}
--- End code ---

well, now i repaired it and it works! it seems i have to learn how to look at the things (not just code). sorry once again and thanks!

ahsjar

Navigation

[0] Message Index

Go to full version