Does spacing matter on switch statements ie

just some bs code but follow me..Does a space after case matter or not?

1
2
3
4
5
6
7
8
9
10
11
12
13
char whatever;
cout <<"Whatever here";
cin something;
switch (something)
{
case 'A': case'B': case 'C':
cout<<"Yes whatever";
break;
case'Z':
cout"whatever";
break;
default:cout<<"spacesmatter on what here?";
}
Last edited on
closed account (SECMoG1T)
Hi, about space? am not sure I got you clearly on that but one thing is for sure about switches, each case forms a new scope, this scope begins from a cases declaration upto a break statement, if there are contingous cases lacking individual break statements then all those cases will evaluate to a single scope for example your line 6 forms a single scope upto line 8 so it would be equivalent to the following if statements

1
2
3
4
5
6
7
8
9
10
if (something=='A'||something=='B'||something=='C')
{
     //.....
         
}

else if (something=='Z')
{
///....
}


So it wouldn't use cout? and as for the spaces I mean does it matter if i type it like case 'A': or case'A': second one has no space first one does, vice versa (if spacing matters )
closed account (SECMoG1T)
So it wouldn't use cout? 

which one are you referring to.

 if i type it like case 'A': or case'A':

Yes and no, if you are using char literals it wouldn't matter because the compiler will be able to differentiate between the case label and the literal however when it comes to integer literals it will definitely matters because a scenario like this would form a new unused label
case1 : //.... but why would you want to write something like that it would affect the readability of your code, i myself would never recommend that.
It would be char literals and as for the cout on the one right before and after the break. ( would they or are they affected by the break . You were saying the break would cause line 6-8 2 show

1
2
else if (something=='Z')
{


rather than
1
2
3
4
 
case 'A': case'B': case 'C':
cout<<"Yes whatever";
break;
closed account (SECMoG1T)
I meant that
1
2
3
case 'A': case'B': case 'C':
cout<<"Yes whatever";
break;


if
something 
was either 'A','B' or 'C' then all statements upto the first break, in this case cout<<"Yes whatever"; would be executed but if something was 'Z' then cout<<"whatever"; would be executed
Yea thats how I wanted it. For example, if you were entering Gradees Whatever would be a F or a E then that cout would be "U Failed or whatever"

I just typed it so it was vague. ( Next time I will type things so people understand it better).
Last edited on
Topic archived. No new replies allowed.