Reputation: 1
I have a doubt: why am I getting outputs when i=3
and when i=7
?
main()
{
int i;
scanf("%d",&i);
switch(i)
{
case 3: printf("message3");
default:
if(i==4)
printf("message4");
case 2:printf("message2");
break;
case 1:printf("Message1");
}
}
Upvotes: 0
Views: 476
Reputation: 108968
The order of the default
case does not determine when that case is executed. The default
case is executed when the switch variable does not match any of the values in a case expression.
For the code above a value of
1
will print "Message 1" when executing the code following the case 1
2
will print "message 2" when executing the code following the case 2
3
will print "message 3message2" when executing the code following the case 3
and fallthrough to default
and fallthrough to case 2
4
will print "message 4message2" when executing the code following the default
and fallthrough to case 2
default
case and fallthrough to case 2
I some times code my switches with the default first
switch (ch) {
default: break; /* do nothing */
case '.': ch = ','; break; /* swap commas */
case ',': ch = '.'; break; /* and periods */
}
Upvotes: 0
Reputation: 2723
@Shubham. Please forgive me if I am repeating what you already know. And in some ways, I am expanding what @Henk already pointed out.
In switch
statement, the role of case
and default
labels are only to determine where the execution should start. Once the first label is determined then rest of the labels have no meaning. The execution is "fall through". Therefore, we have to use break
to stop and exit the switch
.
In your code, if i == 3
then case 3
is the first line of execution. Then case 3
, default
and case 2
are executed followed by break
.
If i
is any value other than 3
then default
is executed followed by case 2
and then exit the switch
. I don't think one will ever get to execute case 1
due to the location of default
.
Upvotes: 2
Reputation: 34615
After case 3
there is no break
. So, switch
falls through and executes default
statement too.
Upvotes: 1
Reputation: 273179
Well,
i == 3 will print message3 and message2
i == 4 will print message4 abd message2
every other value of i will print message2
use break
to terminate processing of a match.
Upvotes: 2