Zilog Z8F0130 User Manual

Page 114

Advertising
background image

Using the Integrated Development Environment

UM013037-1212

90

Zilog Developer Studio II – Z8 Encore!
User Manual

in effect or not. In this sense, the ANSI promotions make the handling of char types incon-
sistent compared to the treatment of other integer types.

It is better coding practice to show such promotions explicitly, as in the following exam-
ple:

int i = (int) a + (int) b;

Then, you get the same answer whether promotions are enabled or disabled. If instead,
you write:

char c = a + b;

then even with ANSI promotions enabled, you do not get the right answer. You did not
anticipate that the arithmetic operation can overflow an 8-bit value. With ANSI promo-
tions disabled, the value of the expression (136) is truncated to fit into the 8-bit result,
again yielding the value (char)

-

120. With ANSI promotions enabled, the expression eval-

uates directly to (char)

-

120.

There are two more types of code constructs that behave differently from the ANSI Stan-
dard when the ANSI promotions are disabled. These occur when an expression involving
unsigned chars is then assigned to a signed int result and when relational operators are
used to compare an unsigned char to a signed char. Both of these are generally poor pro-
gramming practice due to the likelihood of operand signs not being handled consistently.

The following code illustrates the cases in which the code behaves differently depending
on the setting of the

Disable ANSI Promotions

checkbox. When ANSI promotions are

on, the code prints:

START

EQUAL

SIGNED

DONE

When ANSI promotions are off, the code prints:

START

NOT EQUAL

UNSIGNED

DONE

In every case, the difference occurs because when promotions are on, the unsigned chars
are first promoted to signed ints, then the operation occurs; with promotions off, the oper-
ations occur first, then the promotion happens afterward. In every case except the second
test, the code with promotions off has to invoke the ANSI Standard’s rules for how to con-
vert a negative result into an unsigned type – another indication that it is generally poorly
written code for which this setting makes a difference in program behavior.

#include <stdio.h>


unsigned char uch1 = 1;

unsigned char uch2 = 2;

Advertising