Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Chapter 4. Flow Control

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.

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:

if (expression)


if (expression)

Here's a quick code example:

Example 4-1. using_if.c

#include <stdio.h>

  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).

  Published under the terms of the GNU General Public License Design by Interspire