Is *p an lvalue or rvalue

回眸只為那壹抹淺笑 提交于 2019-12-11 05:42:34

问题


In the following code, is *a an rvalue or an lvalue?

#include <stdio.h>

void main()
{
    int b=2;
    int *a=NULL;
    a=&b;
    *a=3;
    printf("%d",*a);

}

回答1:


As exposed in http://en.wikipedia.org/wiki/Value_%28computer_science%29 :

Lvalues have memory addresses that are programmatically accessible to the running program (e.g., via some address-of–operator like "&" in C/C++), meaning that they are variables or dereferenced references to a certain memory location. Rvalues can be lvalues (see below) or non-lvalues

So, *a is an lvalue




回答2:


It is an l-value and can be used in a context of r-value. See the example;

int i, j, *p, *q;
p = &i;
q = &j;

*p = 1; // *p is l-value
*q = 2; // *q is l-value

*p = *q // *q is r-value

As pointed by Charles Bailey in his comment:- The sub-expression *q is still an l-value, it undergoes an l-value to r-value conversion because it is used in a context where an r-value is required.


Now one may think Why *q is still l-value?
Because by definition of r-value an r-value is a temporary value that does not persist beyond the expression that uses it.
In this case value of *q is persists beyond the expression *p = *q.


NOTE:

" * " operator--the deference/indirection operator -- operates on pointer variable, and returns an l-value equivalent to the value at pointer address.




回答3:


According to K&R 2nd edition on p197 §A5:

...an lvalue is an expression referring to an object... for example, if E is an expression of pointer type, then *E is an lvalue expression referring to the object to which E points.

additionally Scott Meyers in his book Effective Modern C++, Introduction - Terminology and Conventions puts another simpler way to determine lvalue/rvalue:

A useful heuristic to determine whether an expression is an lvalue is to ask if you can take its address. If you can, it typically is. If you can’t, it’s usually an rvalue. A nice feature of this heuristic is that it helps you remember that the type of an expression is independent of whether the expression is an lvalue or an rvalue.

therefore, when *p expression appears on the left side it's a lvalue, the right side rvalue.



来源:https://stackoverflow.com/questions/17684476/is-p-an-lvalue-or-rvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!