The value of day must be checked at
every if only until a match is found.
The rest of the tests are then skipped.
Only an else clause is needed to handle
the error conditions.
Using switch
switch (day)
{
case 0:
printf("Sunday\n");
break;
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
default:
printf("Error - unexpected value for day\n");
printf("Should be 0-6. Value is %d\n", day);
break;
}
Note:
The value of day is checked once and control
goes immediately to the correct case.
If that case has a break statement, only the
statements of that case are executed.
Only the default is needed to handle
the error conditions.
Lesson
Cascading ifs (if/else) are more efficient than separate ifs.
The switch is even more efficient, but can only be used for
ints or chars, not floating point numbers. It can't be used
for ranges of values either, so the switch is quite limited
in its usefulness.