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

  




 

 

The GNU C Programming Tutorial - if

Node:if, Next:, Previous:Decisions, Up:Decisions



if

The first form of the if statement is an all-or-nothing choice: if some condition is satisfied, do something; otherwise, do nothing. For example:

if (condition) statement;

or

if (condition)
{
  compound statement
}

In the second example, instead of a single statement, a whole block of statements is executed. In fact, wherever you can place a single statement in C, you can place a compound statement instead: a block of statements enclosed by curly brackets.

A condition is usually an expression that makes some sort of comparison. It must be either true or false, and it must be enclosed in parentheses: (...). If the condition is true, then the statement or compound statement following the condition will be executed; otherwise, it will be ignored. For example:

if (my_num == 0)
{
  printf ("The number is zero.\n");
}

if (my_num > 0)
{
  printf ("The number is positive.\n");
}

if (my_num < 0)
{
  printf ("The number is negative.\n");
}

The same code could be written more compactly in the following way:

if (my_num == 0) printf ("The number is zero.\n");
if (my_num > 0) printf ("The number is positive.\n");
if (my_num < 0) printf ("The number is negative.\n");

It is often a good idea stylistically to use curly brackets in an if statement. It is no less efficient from the compiler's viewpoint, and sometimes you will want to include more statements later. It also makes if statements stand out clearly in the code. However, curly brackets make no sense for short statements such as the following:

if (my_num == 0) my_num++;

The if command by itself permits only limited decisions. With the addition of else in the next section, however, if becomes much more flexible.

 
 
  Published under free license. Design by Interspire