Expert C Programming

(Jeff_L) #1

The unsigned preserving approach (K&R C) says that when an unsigned type mixes with an int or
smaller signed type, the result is an unsigned type. This is a simple rule, independent of hardware, but,
as in the example below, it does sometimes force a negative result to lose its sign!


The value preserving approach (ANSI C) says that when you mix integral operand types like this, the
result type is signed or unsigned depending on the relative sizes of the operand types.


The following program fragment will print a different message under ANSI and pre-ANSI compilers:


main() {


if ( -1 < (unsigned char) 1 )


printf("-1 is less than (unsigned char) 1: ANSI


semantics ");


else


printf("-1 NOT less than (unsigned char) 1: K&R


semantics ");


}


Depending on whether you compile it under K&R or ANSI C, the expression will be evaluated
differently. The same bitpatterns are compared, but interpreted as either a negative number, or as an
unsigned and hence positive number.


Software Dogma


A Subtle Bug


Even though the rules were changed, subtle bugs can and do still occur. In this example, the
variable d is one less than the index needed, so the code copes with it. But the if statement
did not evaluate to true. Why, and what, is the bug?


int array[] = { 23, 34, 12, 17, 204, 99, 16 };


#define TOTAL_ELEMENTS (sizeof(array) /


sizeof(array[0]))


main()


{


int d= -1, x;


/ ... /


if (d <= TOTAL_ELEMENTS-2)


x = array[d+1];


/ ... /

Free download pdf