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 - Comparisons and logic

Node:Comparisons and logic, Next:, Previous:More Special Assignments, Up:Expressions and operators



Comparisons and logic

Comparison operators tell you how numerical values relate to one another, such as whether they are equal to one another, or whether one is greater than the other. Comparison operators are used in logical tests, such as if statements. (See Decisions.)

The results of a logical comparison are always either true (1) or false (0). In computer programming jargon, true and false are the two Boolean values. Note that, unlike real life, there are no "gray areas" in C; just as in Aristotelian logic, a comparison operator will never produce a value other than true or false.

Six operators in C are used to make logical comparisons:

==
is equal to
!=
is not equal to
>
is greater than
<
is less than
>=
is greater than or equal to
<=
is less than or equal to

Important: Remember that many people confuse the equality operator (==) with the assignment operator (=), and this is a major source of bugs in C programs. (See Expressions and values, for more information on the distinction between the == and = operators.)

The operators above result in values, much as the addition operator + does. They produce Boolean values: true and false only. Actually, C uses 1 for "true" and 0 for "false" when evaluating expressions containing comparison operators, but it is easy to define the strings TRUE and FALSE as macros, and they may well already be defined in a library file you are using. (See Preprocessor directives, for information on defining macros.)

#define TRUE  1
#define FALSE 0

Note that although any non-zero value in C is treated as true, you do not need to worry about a comparison evaluating to anything other than 1 or 0. Try the following short program:

#include <stdio.h>

int main ()
{
  int truth, falsehood;

  truth = (2 + 2 == 4);
  falsehood = (2 + 2 == 5);

  printf("truth is %d\n", truth);
  printf("falsehood is %d\n", falsehood);

  exit (0);
}

You should receive the following result:

truth is 1
falsehood is 0

 
 
  Published under free license. Design by Interspire