prev up next   top/contents search

comp.lang.c FAQ list · Question 4.5

Q: I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't

((int *)p)++;

A: 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 either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.) Say what you mean: use

	p = (char *)((int *)p + 1);
or (since p is a char *) simply
	p += sizeof(int);
or (to be really explicit)
	int *ip = (int *)p;
	p = (char *)(ip + 1);

When possible, however, you should choose appropriate pointer types in the first place, rather than trying to treat one type as another.

See also question 16.7.

References: K&R2 Sec. A7.5 p. 205
ISO Sec. 6.3.4
Rationale Sec.
H&S Sec. 7.1 pp. 179-80

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North