### Question 4.5

I have a `char *` pointer that happens to point to some `int`s, and I want to step it over them. Why doesn't

    ((int *)p)++;

work?

In C, a cast operator does not mean ``pretend these bits have a different type, and treat them accordingly''; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with `++`. (It is an anomaly in `pcc`-derived compilers, and an extension in `gcc`, that expressions such as the above are ever accepted.) Say what you mean: use

    	p = (char *)((int *)p + 1);

or (since `p` is a `char *`) simply

    	p += sizeof(int);

Whenever possible, you should choose appropriate pointer types in the first place, instead of trying to treat one type as another.

References: K&R2 Sec. A7.5 p. 205
ANSI Sec. 3.3.4 (esp. footnote 14)
ISO Sec. 6.3.4
Rationale Sec. 3.3.2.4
H&S Sec. 7.1 pp. 179-80

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback