C -- A good compromise between Assembler and high-level programming languages

The C Programming Language

Read more about the History of the C Language.

Language Idioms

Truth

C does not have a dedicated data type for boolean values. Instead, ordinary integer values are normally used to indicate truth. When a numeric value is interpreted in a boolean context (in the test expression of a 'if' or 'while' statement for isntance) it is False when it is zero (0), otherwise it is taken to be True.

The following code snippet illustrates this behaviour:

CodeResult
#include 
void truth(int bound)
{
  int i;
  for (i = bound*-1; i <= bound; i++) {
    printf("%2d is %s\n", i, i ? "TRUE" : "FALSE");
  }
}

int main () { truth(2); return 0; }
-2 is TRUE
-1 is TRUE
 0 is FALSE
 1 is TRUE
 2 is TRUE

There are cases in which relying on this convention creates quite confusing code. A well known example is the memcmp function, which return 0 if the compared memory areas are equivalent. This leads to code like

  if (!memcmp(p1, p2, 4)) { ...
which is confusing to read since the ! operator is normally read as "not". It is recommended to avoid this and use a more clear way to express the same thing:
  if (memcmp(p1, p2, 4) == 0) { ...

Web resources

Last Modified: 2004-11-30 18:50:47
You can view the Source Code of this page