|
|
|
Comparison
Operator
|
|
C has no special type to represent logical or
Boolean values. It improvises by using any of the integral types char, int, short, long, unsigned, with a value of 0 representing
false and any other value representing true. It is rare for logical values to be stored in variables. They are usually generated as required by comparing two numeric values. This is where the comparison operators are used, they compare two numeric values and produce a logical result.
|
C
notation |
Meaning |
|
== |
Equal
to |
|
> |
Grater Than |
|
< |
Less Than |
|
>= |
Grater than
or equal to |
|
<= |
Less than or
equal to
|
|
!=
|
not equal to
|
Note that == is used in comparisons and = is used in assignments.
Comparison operators are used in expressions like the ones below.
In the last example, all arithmetic is done before any comparison is
made.
|
|
Logical Operators
|
|
These
are the usual And, Or and Not operators
|
Symbol |
Meaning |
|
&&
||
! |
AND
OR
Not |
They are frequently used to combine relational operators, for example
x < 20 && x >= 10
In C these logical connectives employ a technique known as lazy evaluation. They evaluate their left hand operand, and then only evaluate the right hand one if this is required. Clearly false && anything is always false, true || anything is always true. In such cases the second test is not evaluated.
Not operates on a single logical value, its effect is to reverse its state. Here is an example of its use.
|
if ( ! acceptable )
printf("Not Acceptable !!\n");
|
|
|
Type conversion
|
|
You can mix the types of values in your arithmetic expressions. char types will be treated as int. Otherwise where types of different size are involved, the result will usually be of the larger size, so a float and a double would produce a double result. Where integer and real types meet, the result will be a double.
There is usually no trouble in assigning a value to a variable of different type. The value will be preserved as expected except
where.
-
The variable is too small to hold the value. In this case it will be corrupted (this is bad).
-
The variable is an integer type and is being assigned a real value. The value is rounded down. This is often done deliberately by the programmer.
Values passed as function arguments must be of the correct type. The function has no way of determining the type passed to it, so automatic conversion cannot take place. This can lead to corrupt results. The solution is to use a method called casting which temporarily disguises a value as a different type.
eg. The function sqrt finds the square root of a double.
|
int i = 256;
int root
root = sqrt( (double) i);
|
The cast is made by putting the bracketed name of the required type just before the value. (double) in this example. The result of
sqrt( (double) i); is also a double, but this is automatically converted to an int on assignment to root.
|
|
Back
|
|
Next
|
|
|