Boolean values
Of significance,
and a very common cause of errors in C programs,
is that C standards, prior to ISO-C99,
had no Boolean datatype.
Historically,
an integer value of zero evaluated equivalent to a Boolean value of false;
any non-zero integer value evaluated as true.
You may read some older C code:
|
which may be badly and accidently coded as:
|
so, employ defensive programming:
|
int initialised = 0; // set to false
....
if(! initialised) {
// initialisation statements;
.....
initialised = 1; // set to true
}
|
|
int initialised = 0; // set to false
....
if(initialised = 0) {
// initialisation statements;
.....
initialised = 1; // set to true
}
|
|
int initialised = 0; // set to false
....
if(0 = initialised) { // invalid syntax!
// initialisation statements;
.....
initialised = 1; // set to true
}
|
|
In the second example,
the conditional test always evaluates to false,
as the single equals character requests an assignment, not a comparison.
It is possible (and occassionally reasonable)
to perform an assignment as part of a Boolean condition -
you'll often see:
while( (nextch = getc(file) ) != EOF ) {....
Whenever requiring the true and false constants
(introduced in C99),
we need to provide the line:
#include <stdbool.h>
CITS2002 Systems Programming, Lecture 2, p10, 24th July 2024.
|