L值到R值转换

时间:2013-08-31 10:32:41

标签: c expression lvalue-to-rvalue

这里的网站说: 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

Ques.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:

Plzz用exception 3解释example

2 个答案:

答案 0 :(得分:3)

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

  

6.3.2.1

     

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

答案 1 :(得分:1)

对问题2的回答。

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

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

*q;

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