Programming in C

(Barry) #1
Character Operations 227

If compareStringsreturns a value of –1—indicating that dictionary[mid].wordis
less than search—lookupsets the value of lowto mid+ 1. If compareStringsreturns
1—indicating that dictionary[mid].searchis greater than search—lookupsets the
val ue of highto mid– 1. If neither –1 nor 1 is returned, the two strings must be equal,
and, in that case,lookupreturns the value of mid, which is the entry number of the
word in the dictionary.
If loweventually exceeds high, the word is not in the dictionary. In that case,lookup
returns –1 to indicate this “not found” condition.


Character Operations


Character variables and constants are frequently used in relational and arithmetic expres-
sions.To properly use characters in such situations, it is necessary for you to understand
how they are handled by the C compiler.
Whenever a character constant or variable is used in an expression in C, it is automat-
ically converted to, and subsequently treated as, an integer value.
In Chapter 6, “Making Decisions,” you saw how the expression


c >= 'a' && c <= 'z'


could be used to determine if the character variable ccontained a lowercase letter. As
mentioned there, such an expression could be used on systems that used an ASCII char-
acter representation because the lowercase letters are represented sequentially in ASCII,
with no other characters in-between.The first part of the preceding expression, which
compares the value of cagainst the value of the character constant 'a', is actually com-
paring the value of cagainst the internal representation of the character 'a'. In ASCII,
the character 'a'has the value 97 , the character 'b'has the value 98 , and so on.
Therefore, the expression c >= 'a'is TRUE (nonzero) for any lowercase character con-
tained in cbecause it has a value that is greater than or equal to 97. However, because
there are characters other than the lowercase letters whose ASCII values are greater than
97 (such as the open and close braces), the test must be bounded on the other end to
ensure that the result of the expression is TRUE for lowercase characters only. For this
reason,cis compared against the character 'z',which, in ASCII, has the value 122.
Because comparing the value of cagainst the characters 'a'and 'z'in the preceding
expression actually compares cto the numerical representations of 'a'and 'z', the
expression


c >= 97 && c <= 122


could be equivalently used to determine if cis a lowercase letter.The first expression is
preferred, however, because it does not require the knowledge of the specific numerical
values of the characters 'a'and 'z', and because its intentions are less obscure.
The printfcall


printf ("%i\n", c);

Free download pdf