Add Book to My BookshelfPurchase This Book Online

Appendix A - Significant Changes in ANSI C

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Expressions
Perhaps the most significant divergence of ANSI C from widely accepted practice is in expression evaluation. In original K&R C, unsigned specified exactly one type. There were no unsigned chars, unsigned shorts, or unsigned longs. This is not to say that most compilers did not support these types, just that they were never “official.” Naturally, since the rules for how these unofficial types behaved in expressions in which they were mixed with other types did not exist, different compiler implementors used different rules.
In most C compilers, a “sign preserving” rule is used. If an unsigned type needs to be widened, it is widened to a larger unsigned type. When an unsigned type mixes with a signed type, the result is an unsigned type. This makes a certain amount of sense, but can lead to unexpected results in certain situations. For example, subtracting unsigned short 5 from unsigned short 3 will produce a large unsigned number with the same bit pattern as -2.
ANSI C, on the other hand, specifies that a “value preserving” rule should be used. When an unsigned type smaller than an int needs to be widened, it is widened to a signed int if that is large enough to hold the type, otherwise it is widened to an unsigned int. This produces more intuitive behavior in cases like the above (in which the result would be a signed int -2), and makes no difference in most other cases. However, programs that rely on the earlier behavior will need to be modified (usually by inserting appropriate typecasts) if they are to work correctly.

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback