In C++, pre-increment operator gives lvalue because incremented object itself is returned, not a copy. But in C, it gives rvalue. Why?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
C doesn't have references. In C++
++i
returns a reference toi
(lvalue) whereas in C it returns a copy(incremented).C99 6.5.3.1/2
‘‘value of an expression’’ <=> rvalue
However for historical reasons I think "references not being part of C" could be a possible reason.
Off the top of my head, I can't imagine any useful statements that could result from using a pre-incremented variable as an lvalue. In C++, due to the existence of operator overloading, I can. Do you have a specific example of something that you're prevented from doing in C, due to this restriction?
C99 says in the footnote (of section $6.3.2.1),
Hope that explains why
++i
in C, returns rvalue.As for C++, I would say it depends on the object being incremented. If the object's type is some user-defined type, then it may always return lvalue. That means, you can always write
i++++++++
or++++++i
if type ofi
isIndex
as defined here:Undefined behavior and sequence points reloaded