Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pre-increment operator gives rvalue in C?

Tags:

c++

c

lvalue

rvalue

In C++, pre-increment operator gives lvalue because incremented object itself is returned, not a copy. But in C, it gives rvalue. Why?

like image 610
Happy Mittal Avatar asked Jan 26 '11 07:01

Happy Mittal


People also ask

What is the use of pre increment in C?

1) Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression.

Why is Preincrement more efficient?

If the counter is a fundamental type and the result of increment is not used, then it makes no difference whether you use post/pre increment. If the counter is not a fundamental type and the result of the increment is not used and optimizations are disabled, then pre increment may be more efficient.

How does pre increment operator work?

The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression. if the expression is a = ++b; and b is holding 5 at first, then a will hold 6.

What is a rvalue in C?

An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.


1 Answers

C doesn't have references. In C++ ++i returns a reference to i (lvalue) whereas in C it returns a copy(incremented).

C99 6.5.3.1/2

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++Eis equivalent to (E+=1).

‘‘value of an expression’’ <=> rvalue

However for historical reasons I think "references not being part of C" could be a possible reason.

like image 170
Prasoon Saurav Avatar answered Oct 04 '22 19:10

Prasoon Saurav