switch

C

Christopher

In a switch statement must a supply a default or what is the default by
default?

Is

switch(foo)
{
case 1:
return 1;
default:
break;
}

the same as

switch(foo)
{
case 1:
return 1;
}

Thanx,
Christopher
 
A

Attila Feher

Christopher said:
In a switch statement must a supply a default or what is the default
by default?

You supply one if you want to. If you do not supply one then if none of the
labels match the switch will be "ignored", meaning that it means what you
just wrote below:
 
C

chris

Christopher said:
In a switch statement must a supply a default or what is the default by
default?

Is

switch(foo)
{
case 1:
return 1;
default:
break;
}

the same as

switch(foo)
{
case 1:
return 1;
}

Yes, it is.

If you don't specify a default and the input doesn't match any of the
cases, then simply nothing in the switch is called.
 
G

Gavin Deane

Christopher said:
In a switch statement must a supply a default or what is the default by
default?

Is

switch(foo)
{
case 1:
return 1;
default:
break;
}

the same as

switch(foo)
{
case 1:
return 1;
}

They are the same.
GJD
 
M

Mike Wahler

Christopher said:
In a switch statement must a supply a default or what is the default by
default?

Is

switch(foo)
{
case 1:
return 1;
default:
break;
}

the same as

switch(foo)
{
case 1:
return 1;
}

Thanx,
Christopher

The first 'case' value which matches the 'argument'
to 'switch' causes that 'case clause' to be executed,
and continues linearly until a 'break' statement or
the closing brace is encountered. If none of the 'cases'
match and a 'default' case is defined, then that portion
is executed, also until a 'break' or the closing brace
is encountered. If none of the 'cases' match, and no
'default' case is defined, control flow passes to after
the closing brace.

Note that the 'default' case need not be listed last.

Some like to always use a 'default' case whether it
does anything or not, but you only really need it
if you actually want to execute some code in the
'default' case.


-Mike
 
R

Ron Natalie

Mike Wahler said:
The first 'case' value which matches the 'argument'
to 'switch' causes that 'case clause' to be executed,

Actually, it's the only case that matches. The language
does not allow for duplicate cases.
 
M

Mike Wahler

Ron Natalie said:
Actually, it's the only case that matches. The language
does not allow for duplicate cases.

Of course. I didn't even consider that.
Actually, I didn't know for sure if duplicates
were allowed, since I never had occasion to
try to use them. What would be the point, right? :)

Thanks.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,813
Members
47,357
Latest member
sitele8746

Latest Threads

Top