Taking actions based on decisions
C provides two sytles of decision making: branching and looping. Branching is deciding what actions to take and looping is deciding how many times to take a certain action.
Branching is so called because the program chooses to follow one branch or another. The if statement is the most simple of the branching statements. It takes an expression in parenthesis and an statement or block of statements (surrounded by curly braces). if the expression is true (evaluates to non-zero) then the statement or block of statements gets executed. Otherwise these statements are skipped. if statements take the following form:
Here's a quick code example:
Example 4-1. using_if.c
#include <stdio.h> int main() { int cows = 6; if (cows > 1) printf("We have cows\n"); if (cows > 10) printf("loads of them!\n"); return 0; }
ciaran@pooh:~/book$ gcc -Wall -Werror -o cows using_if.c ciaran@pooh:~/book$ ./cows We have cows ciaran@pooh:~/book$
The second printf() statement does not get executed because it's expression is false (evaluates to zero).