为什么这个结果不是左值? [英] Why isn't the result of this cast an lvalue?

查看:31
本文介绍了为什么这个结果不是左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些关于这种奇怪行为的建议——让我们看看这段代码:

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

int ** p;

编译没有任何问题:

p++;

但是这个:

((int**)p)++;

给我这个错误信息:error: lvalue required as increment operation".

我正在将 p 转换为它已经是的类型,没有任何变化,那么问题是什么?这是我遇到的问题的简化版本,当我试图编译一个旧的gdb 的版本.所以我想,这奏效了,并且发生了一些变化.知道第二个例子有什么问题吗?

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?

推荐答案

旧版本的 gcc 支持称为左值强制转换"的东西——如果您强制转换为左值,则结果为左值,并且可以这样处理.它的主要用途是允许您将指针增加一个对应于不同大小的数量:

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 */

这个扩展在 gcc v3.0 前后被弃用了一段时间,并在 gcc v4.0 中被移除

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

要在较新版本的 gcc 中执行相同的操作,您需要进行加法和赋值(而不是增量),将指针转换为加法类型并返回赋值:

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.

这篇关于为什么这个结果不是左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆