Decisions: if, else and switch
A useful program makes decisions: it does one thing or another depending on the data. In C decisions are expressed with if and else for conditions, and with switch when you must choose among many specific values of an integer. Mastering these structures lets you write programs that react to user input and to the results of their own calculations.
if, else if and else
The condition goes in parentheses and is read as true if it is nonzero. If the block has a single statement the braces are optional, but I recommend always using them: omitting them causes errors when you add a second line and expect it to belong to the if as well. The else if branches are evaluated in order and only the first one whose condition holds runs; else catches everything else.
#include <stdio.h>
int main(void) {
int score;
printf("Score (0-100): ");
if (scanf("%d", &score) != 1) {
printf("Not a number.\n");
return 1;
}
if (score < 0 || score > 100) {
printf("Out of range.\n");
} else if (score >= 90) {
printf("Grade A\n");
} else if (score >= 70) {
printf("Grade B\n");
} else if (score >= 50) {
printf("Grade C\n");
} else {
printf("Fail\n");
}
return 0;
}Notice the order: first invalid values are discarded and then the ranges are tested from highest to lowest. Since they are chained, there is no need to write score >= 70 && score < 90, because if we reached that branch we already know it is not greater than or equal to 90. A frequent mistake is putting a semicolon right after the parenthesis: if (x > 0); makes the if control an empty statement and the following block always runs.
The ternary operator
To choose between two values there is the compact form condition ? value_if_true : value_if_false. It is an expression, not a statement, so it can be used inside another. Use it only when it stays readable; if you nest several, a normal if is clearer.
switch
switch compares an integer (or char) expression with several case labels. When one matches, it runs from there downward until it finds a break; if you forget it, execution continues into the next case, behavior called fall-through. It is sometimes useful on purpose, as in the vowels example, but it is almost always an oversight. The default label catches unforeseen values. It does not accept strings or reals.
#include <stdio.h>
int main(void) {
char letter;
printf("Letter: ");
if (scanf(" %c", &letter) != 1) {
return 1;
}
switch (letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("vowel\n"); /* several labels share one block */
break;
case ' ':
printf("space\n");
break;
default:
printf("other\n");
break;
}
int n = 7;
printf("%d is %s\n", n, (n % 2 == 0) ? "even" : "odd");
return 0;
}A practical rule to choose: use if for ranges and compound conditions, and switch to compare the same variable with discrete values, such as menu options or command codes. Declaring variables inside a case requires opening your own braces, because labels do not create a new scope and the compiler complains if you jump over an initialization.
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères