C strongly typed?

Nick Maclaren nmm at cl.cam.ac.uk
Thu Mar 8 22:35:32 AEST 1990


Henry Spencer writes:

> ....  C's type system is not extensible unless
> you count "struct", but the language is strongly typed -- mixing random
> types is not allowed.

I am afraid that I must disagree with this.  While mixing RANDOM types is
not allowed, even ANSI C permits a bewildering variety of type punning.
For example:

    double x, y;
    memcpy(&x,&y,sizeof(double));

The ANSI standard (and K&R) explicitly require that any data type may be
treated as an array of characters (under certain circumstances, such as
the above).  A huge proportion of the library relies upon this to work at
all (e.g. much of string.h, some of stdlib.h, some of stdio.h).

    union {void *a; char *b;} fred;
    fred.a = ...;
    ... = fred.b;

This example is a curiosity in ANSI C:  while it is illegal, and the compiler
is entitled to throw it out, it is also required to work!  The reason is that
'char *' and 'void *' are different types but are required to have the same
representation and alignment.

There are a large number of more obscure cases, many of which are relied
upon by traditional C programs.  Good, portable ones avoid such constructions
if at all possible, but sometimes their use is essential.

Nick Maclaren
University of Cambridge Computer Laboratory
nmm at cl.cam.ac.uk



More information about the Comp.lang.c mailing list