[Solved] lvalue required as increment operand error

#include <stdio.h>

int main()
{
   int i = 10;
   printf("%dn", ++(-i)); // <-- Error Here
}

What is wrong with ++(-i)? Please clarify.

Enquirer: Wei

||

Solution #1:

-i generates a temporary and you can’t apply ++ on a temporary(generated as a result of an rvalue expression). Pre increment ++ requires its operand to be an lvalue, -i isn’t an lvalue so you get the error.

Respondent: Prasoon Saurav

Solution #2:

The ++ operator increments a variable. (Or, to be more precise, an lvalue—something that can appear on the left side of an assignment expression)

(-i) isn’t a variable, so it doesn’t make sense to increment it.

Respondent: SLaks

Solution #3:

You can’t increment a temporary that doesn’t have an identity. You need to store that in something to increment it.
You can think of an l-value as something that can appear on the left side of an expression, but in eventually you’ll need to think of it in terms of something that has an identity but cannot be moved (C++0x terminology). Meaning that it has an identity, a reference, refers to an object, something you’d like to keep.

(-i) has NO identity, so there’s nothing to refer to it. With nothing to refer to it there’s no way to store something in it. You can’t refer to (-i), therefore, you can’t increment it.

try i = -i + 1

#include <stdio.h>

int main()
{
   int i = 10;
   printf("%dn", -i + 1); // <-- No Error Here
}
Respondent: Lee Louviere

Solution #4:

Try this instead:

#include <stdio.h>

int main()
{
   int i = 10;
   printf("%dn", (++i) * -1);
}
Respondent: Localghost

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.