09.06.2013 Views

Intel XENIX 286 Programmers Guide (86) - Tenox.tc

Intel XENIX 286 Programmers Guide (86) - Tenox.tc

Intel XENIX 286 Programmers Guide (86) - Tenox.tc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>XENIX</strong> Programming C Language Portability<br />

This is reliable because C guarantees all characters to be positive. The use of hardcoded<br />

octal constants is subject to sign extension. For example, the following program<br />

prints "ff80" on a PDP-11:<br />

main( )<br />

{<br />

pri ntf( II% x\n II, '\200');<br />

}<br />

Type conversion also takes place when arguments are passed to functions. Types char<br />

and short become int. Machines that sign extend char can produce unexpected results.<br />

For example, the following program gives -128 on some machines:<br />

char c = 128;<br />

printf(" % d\nll ,c);<br />

This is because c is converted to int before being passed to the function. The function<br />

itself has no knowledge of the original type of the argu ment and is expecting an int.<br />

The correct way to handle this is to code defensively and allow for the possibility of sign<br />

extension:<br />

char c = 128;<br />

printf("%d\n", c & Oxff) ;<br />

Functions with Variable Number of Argu ments<br />

Functions with a variable number of arguments present a particular portability problem<br />

if the type of the arguments is also variable. In such cases, the code depends on the size<br />

of various data types.<br />

<strong>XENIX</strong> has an include file, /usr/include/varargs.h, that contains macros for use in<br />

variable argument functions to access the argu ments in a portable way:<br />

typedef char *va list;<br />

#define va del int va alist;<br />

#define va -start(list) list = (char *) &va alist<br />

#define va-end(list)<br />

#define va = arg(l ist,mode) ((mode *)(list + = sizeof(mode) ) ) [- 1 1<br />

The va endO macro is not currently required. Use of the other macros will be<br />

demonstrated by an example of the fprintf library routine. This has a first argument of<br />

type FILE * and a second argu ment of type char *. Subsequent arguments are of<br />

unknown type and number at compilation time. They are determined at run time by the<br />

contents of the control string, argument 2.<br />

A-9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!