需要左值作为增量操作数错误
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
++(-i)
有什么问题吗?请澄清。
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
What is wrong with ++(-i)
? Please clarify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
-i
生成一个临时变量,并且您不能将++
应用于临时变量(作为右值表达式的结果生成)。预增量++
要求其操作数是左值,-i
不是左值,因此会出现错误。-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.++
运算符递增变量。 (或者,更准确地说,左值 - 可以出现在赋值表达式的l左端的东西)(-i)
不是变量,因此增加它没有意义。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.您无法增加没有身份的临时。您需要将其存储在某个东西中以增加它。
您可以将左值视为可以出现在表达式左侧的东西,但最终您需要将其视为具有同一性但无法移动的东西(C++0x 术语)。这意味着它有一个身份、一个引用、指一个对象、您想要保留的东西。
(-i) 没有身份,所以没有什么可以引用它。由于没有任何东西可以引用,因此无法在其中存储任何内容。您无法引用 (-i),因此无法增加它。
尝试 i = -i + 1
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
试试这个:
Try this instead: