简体   繁体   English

需要左值作为增量操作数错误

[英]lvalue required as increment operand error

#include <stdio.h>

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

What is wrong with ++(-i) ? ++(-i)有什么问题? Please clarify.请说清楚。

-i generates a temporary and you can't apply ++ on a temporary(generated as a result of an rvalue expression). -i生成一个临时文件,您不能将++应用于临时文件(作为右值表达式的结果生成)。 Pre increment ++ requires its operand to be an lvalue, -i isn't an lvalue so you get the error. Pre increment ++要求它的操作数是左值, -i不是左值,所以你会得到错误。

The ++ operator increments a variable. ++运算符递增一个变量。 (Or, to be more precise, an lvalue —something that can appear on the l eft side of an assignment expression) (或者,更准确地说,一个左值——可以出现在赋值表达式左侧的东西)

(-i) isn't a variable, so it doesn't make sense to increment it. (-i)不是变量,因此增加它没有意义。

You can't increment a temporary that doesn't have an identity .您不能增加没有 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).您可以将左值视为可以出现在表达式左侧的东西,但最终您需要将其视为具有标识但不能移动的东西(C++0x 术语)。 Meaning that it has an identity, a reference, refers to an object, something you'd like to keep.这意味着它有一个身份,一个引用,指的是一个 object,你想保留的东西。

(-i) has NO identity, so there's nothing to refer to it. (-i) 没有身份,所以没有什么可以引用它。 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.您不能引用 (-i),因此,您不能增加它。

try i = -i + 1试试 i = -i + 1

#include <stdio.h>

int main()
{
   int i = 10;
   printf("%d\n", -i + 1); // <-- No Error Here
}

Try this instead:试试这个:

#include <stdio.h>

int main()
{
   int i = 10;
   printf("%d\n", (++i) * -1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM