3.3. More logical expressionsThis chapter has already shown how C makes no distinction between
‘logical’ and other values. The relational operators all give a
result of while (a<b)... while (a).... if ( (c=getchar()) != EOF )... No experienced C programmer would be surprised by any of them. The second
of them, What we need now is a way of writing more complicated expressions
involving these logical true and false values. So far, it has to be done
like this, when we wanted to say
if (a < b){
if (c < d)...
}
It will not be a source of great amazement to find that there is a way of expressing such a statement. There are three operators involved in this sort of operation: the logical
Do not confuse One special feature of the logical operators, found in very few of the
other operators, is their effect on the sequence of evaluation of an
expression. They evaluate left to right (after precedence is taken into
account) and every logical expression ceases evaluation as soon as the
overall result can be determined. For example, a sequence of
if (a!=0 && b/a > 5)... /* alternative */ if (a && b/a > 5) In either version The unary NOT is simple. It isn't all that common to see it in use largely because most expresssions can be rearranged to do without it. The examples show how. if (!a)... /* alternative */ if (a==0)... if(!(a>b)) /* alternative */ if(a <= b) if (!(a>b && c<d))... /* alternative */ if (a<=b || c>=d)... Each of the examples and the alternatives serve to show ways of avoiding
(or at least doing without) the Most expressions using these logical operators work out just about right in terms of the precedence rules, but you can get a few nasty surprises. If you look back to the precedence tables, you will find that there are some operators with lower precedence than the logical ones. In particular, this is a very common mistake:
if(a&b == c){...
What happens is that |
The C BookThis book is published as a matter of historical interest. Please read the copyright and disclaimer information. GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested. |
|
West Yorkshire Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |