4.1. Branching
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;
}
When compiled and run this program will display:
[email protected]:~/book$ gcc -Wall -Werror -o cows using_if.c
[email protected]:~/book$ ./cows
We have cows
[email protected]:~/book$
The second printf() statement does not get
executed because it's expression is false (evaluates to zero).