Instructions
Create the If Else Statement
1Begin with the basics. The basic structure of every If Else statement in C takes this form:
if (condition) action;
2
Bracket your action correctly. The action can be a single command, or more often a series of commands, inside curly brackets.
Create the Condition
1Realize that a condition is anything that returns 0 (false) or anything else (true).
2
Know that the most common kind is a comparison between variables or values:
== equality
!= inequality
> greater than
< less than
>= greater than or equal to
<= less than or equal to
3
Compare numeric and character types, if you so choose, but be careful: characters compare based on the character set in use on that system, and that may be different some day on some other operating system.
4
Do not try to compare arrays or structures directly. Instead, write a function that will carry out the comparison.
5
Understand that C standard libraries include such functions for strings. See strcmp(), stricmp(), and strncmp().
6
Use assignment to return the value that was assigned.
if ((x = malloc(100)) == NULL) abort();The value returned by malloc() is both saved to x and compared to NULL, making your code more concise.
7
Use a tried and true technique: It's common to have functions return 1 on success and 0 on failure, and use them as a condition.
8
Realize that in C, everything has a value, so anything can be the condition. For instance, a comparison to 0 is usually redundant.
if (x) printf("x is not zero\n");
Combine and Modify Conditions
1Use the ! (not) operator to negate, or reverse, a condition.
if (!x) printf("x is zero\n");
2
Use && (and) and || (or) to combine conditions logically. && requires both conditions true to be true; || is true if either one is.
3
Use parentheses to control how conditions are evaluated.
if (x == 5 and y == 6 or z == 7)is ambiguous;
if ((x == 5 and y == 6) or z == 7)is clear.
4
Take advantage of C's limitations. C will always evaluate the parts of a && or || from left to right, and stop evaluating once it knows the answer. Use this to your advantage. For example,
if (x and *x)prevents runtime errors in case x is NULL, since C will have stopped evaluating before the dereference.
Add Else Clauses
1Add an alternative action if the condition is false, simply by adding the word else after the action, then another action, like so:
if (condition) action; else action;
2
Know that both actions can be, and typically are, whole groups of commands included in curly brackets, like this:
if (condition) {
do stuff;
} else {
do other stuff;
}
3
Realize that it's common for the Else statement to include another If, to select the right one from a whole set of cases. Consider this example:
if (x <= 80) {
grade = 'C';
} else if (x <= 90){
grade = 'B';
} else {
grade = 'A';
}
SHARE