【问题标题】:L-value to R-value conversionL 值到 R 值的转换
【发布时间】:2013-08-31 10:32:40
【问题描述】:

这里的网站说: http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc05lvalue.htm

If an lvalue appears in a situation in which the compiler expects an rvalue, 
the compiler converts the lvalue to an rvalue.

An lvalue e of a type T can be converted to an rvalue if T is not a function or        
array type. The type of e after conversion will be T. 

Exceptions to this is:

    Situation before conversion             Resulting behavior

1) T is an incomplete type                  compile-time error
2) e refers to an uninitialized object      undefined behavior
3) e refers to an object not of type T      undefined behavior

问题1:

考虑以下程序,

int main()
{   
    char p[100]={0};      // p is lvalue
    const int c=34;       // c non modifiable lvalue

    &p; &c;               // no error fine beacuse & expects l-value
    p++;                  // error lvalue required  

    return 0;
}

我的问题是,为什么在表达式 (p++) ++(postfix) 中需要 l-values 而数组是 l-value 那么为什么会出现这个错误? gcc 错误:需要左值作为增量操作数|

问题2:

请用example 解释exception 3

【问题讨论】:

  • 数组(静态)的地址不是左值。
  • 我不明白您的问题 (#1) 与您引用的段落有何关系。使用后缀++ 不涉及从左值到右值的转换。
  • @nickie 当我编译这个语句 p++ 我从 gcc 得到编译时错误
  • 是的,当然,@cnicutar 在下面解释了这一点。我认为,这只是您的问题的标题不准确。不涉及左值和右值之间的转换。
  • @nikie p++ 中 p 的类型是什么,先生,您能否详细说明为什么会出现错误?评估 p++ 时究竟发生了什么

标签: c expression lvalue-to-rvalue


【解决方案1】:

数组确实是左值,但它们不可修改。标准说:

6.3.2.1

可修改的左值是没有数组类型的左值

【讨论】:

  • 另外,在 6.5.2.4 中,后缀 ++ 的操作数应该是一个可修改的左值。您的 p 不是可修改的左值,如正确回答。
【解决方案2】:

问题 2 的答案。

假设您有一个double 类型的对象。您获取一个指针并将其转换为不同的指针类型。然后使用新指针取消引用该对象。这是未定义的行为。

double x = 42.0;
double *p = &x;
int *q = (int *) p;

*q;

这里,*qint 类型的左值,它不引用 int 类型的对象。

【讨论】:

    猜你喜欢
    • 2014-11-25
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2017-11-24
    相关资源
    最近更新 更多