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
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
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)
  statement;
     

or

if (expression)
  {
    statement1;
    statement2;
    statement3;
  }
     

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

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