Page 42 - Programming Microcontrollers in C
P. 42
Operators and Expressions 27
is a character c, and it is necessary to determine if this character is a
letter. In such a case, the following logical expression might be used:
if( c >= ‘A’ && c <= ‘Z’ || c >= ‘a’ && c <= ‘z’)
The logical and operator && has lower precedence than any of the
relational operators, so the relational expressions will each be evalu
ated prior to the && operations. If upon entering this expression, c is
equal to the character ‘5’, which is arithmetically smaller than any
of the letters, the first term c >= ‘A’ will be FALSE. Therefore, the
result of the first logical and expression is known to be FALSE
without evaluating the term c <= ‘Z’. The evaluation will then
skip to the third term c >= ‘a’, and the term c <= ‘Z’ will not be
evaluated. In this case, the character ‘5’ will be smaller than the
character ‘a’ so that the second and expression will also be FALSE.
Therefore, the logical value will be known after evaluation of only
two of the logical terms of the argument rather than having to evalu
ate all four of the terms.
EXERCISES
1. Write a function that converts a character that is a letter to lower
case.
2. Leap years occur every four years unless the year happens to be
divisible by 100. Any year divisible by 400 is a leap year, however.
Write a logical expression that will return TRUE if the given year
is a leap year and FALSE if it is not.
Type Conversions Within Expressions
Implied in our earlier discussions on variable types, different data
types not only occupy different width in memory, some may be com
pletely incompatible when attempting to execute operations involving
mixed data types. In earlier languages, it was up to the programmer
to guarantee that the data types involved with an operation were the
same. C resolves this problem, and the compiler will select the proper
data type to complete operations on mixed data types.
Each data type has an implied width. When an operation is to be
executed on mixed data types, the widths of the two types are evalu
ated, and the lesser width operand is promoted to the type of the