1

In the following code segment, I was expecting the answer to be 5 but it shows compile time error:

#include <stdio.h>
int main()
{
    int i = 4;
    printf("%d", (++i)++);
    return 0;
}

What is the reason?. Here ++i returns an l value right So we could increment it right?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
san45
  • 459
  • 1
  • 6
  • 15

2 Answers2

5

(++i) returns an rvalue. This cannot be incremented.

Igor Popov
  • 2,588
  • 17
  • 20
  • is ++i returns lvalue? – san45 Oct 26 '13 at 11:13
  • 1
    @san45 Did you bother reading this one-liner? "(++i) returns an rvalue" -- so then does it return an lvalue? **No it doesn't. Period.** –  Oct 26 '13 at 11:14
  • had a comment below saying that ++i returns lvalve that why – san45 Oct 26 '13 at 11:18
  • 1
    @san45 ++i operator returns a "value", but not the variable itself. So it's address can not be retrieved, which disregards it as an lvalue. – Igor Popov Oct 26 '13 at 11:20
  • Some useful links: http://stackoverflow.com/questions/16399485/condition-for-lvalues-and-rvalues-in-c , http://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c/ – Igor Popov Oct 26 '13 at 11:29
4

postincrement\decrement or preincrement\decrement requires lvalue and returns rvalue. that's why you are getting an error.

++i =>returns rvalue

(rvalue)++ => error

In c++ the situation is different because of reference types.In c we don't have any reference type.

in c++

++i => returns reference to i that is lvalue.

lvalue++ => Way to go! 

Demo for c++

even it is working, It is a undefined behavior. You should not modify the same variable more than once in a same statement.

Arpit
  • 12,767
  • 3
  • 27
  • 40
  • 3
    It's not UB. It doesn't even compile. –  Oct 26 '13 at 11:13
  • @H2CO3 Yeah! corrected. – Arpit Oct 26 '13 at 11:21
  • this is the same in C++ also right ? – san45 Oct 26 '13 at 11:26
  • @san45 **NO!** refrence is magic. – Arpit Oct 26 '13 at 11:27
  • You know what's magic? Undefined behavior. I think this should be mentioned instead of giving the impression that `(++i)++` is correct in C++. – Pascal Cuoq Oct 26 '13 at 11:48
  • @PascalCuoq Oh! yes. you are right. It was my first line when i answered it but then removed it because of C tag. And later while editing i forgot to mention it. :P. Copied from the draft. – Arpit Oct 26 '13 at 11:51
  • 1
    I think your statement, *"You can not modify the same variable more than one time in a same statement."* is misleading.... you ***can*** do it, it is allowed. You just cannot predict the results. – abelenky Oct 26 '13 at 12:25