Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c - Why isn't the result of this cast an lvalue?

I need some advice with this strange behavior – lets have this code:

int ** p;

This compiles without any trouble:

p++;

But this:

((int**)p)++;

Gives me this error message: “error: lvalue required as increment operand”.

I am casting to p to the type it already is, nothing changes, so what is the problem? This is simplified version of problem I came across, when I was trying to compile one old version of gdb. So I suppose, that this worked and something changed. Any idea what is wrong with the second example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Old versions of gcc support something called "lvalue casts" -- if you cast something that is an lvalue the result is an lvalue and can be treated as such. The main use for it is allowing you to increment a pointer by an amount corresponding to a different size:

int *p;
++(char *)p;  /* increment p by one byte, resulting in an unaligned pointer */

This extension was deprecated some time around gcc v3.0 and removed in gcc v4.0

To do the equivalent thing in more recent versions of gcc, you need do an addition and assignment (instead of an increment) casting the pointer to the type for the addition and back for the assignment:

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

Note that trying to dereference the pointer after this is undefined behavior, so don't count on it doing anything useful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...