← The C Language
Lesson 15 of 77 · 10 XP
Choice: switch
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
switch compares an integer value (or a char) with a set of constants:
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
default:
printf("unknown operation\n");
}
Its main feature is fall-through: without break, execution continues into the next case. Sometimes this is done on purpose:
case 'y':
case 'Y':
printf("yes\n"); // for both 'y' and 'Y'
break;
But more often a forgotten break is a bug. You can't compare strings in a switch: only integers and characters.
Task. A simple calculator: read an expression of the form 7 * 3 (a number, an operation, a number) and print the result. Operations: + - * / (integer division). For division by zero print error, and for an unknown operation print unknown.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.