[英]Why Pointer assignment shows lvalue error when assignments look appropriate?
I am given a piece of code for which we have to guess output. 我得到了一段代码,我们必须猜测输出。
My Output: 60 我的输出:60
#include <stdio.h>
int main()
{
int d[] = {20,30,40,50,60};
int *u,k;
u = d;
k = *((++u)++);
k += k;
(++u) += k;
printf("%d",*(++u));
return 0;
}
Expected: k = *((++u)++)
will be equal to 30 as it will iterate once(++u) and then will be iterated but not assigned. 预期:
k = *((++u)++)
将等于30,因为它将迭代一次(++ u)然后将被迭代但未分配。 So we are in d[1]. 所以我们在d [1]。
(++u) += k
here u will iterate to next position, add k to it and then assign the result to further next element of u. (++u) += k
这里你将迭代到下一个位置,向它添加k然后将结果分配给u的下一个元素。
Actual result: 实际结果:
main.c: In function ‘main’:
main.c:16:16: error: lvalue required as increment operand
k = *((++u)++);
^
main.c:18:11: error: lvalue required as left operand of assignment
(++u) += k;
And this has confused me further in concepts of pointers. 这使我在指针的概念中更加困惑。 Please help.
请帮忙。
As the compiler has told you, the program is not valid C. 正如编译器告诉你的那样,程序无效C.
In C, pre-increment results in an rvalue expression , which you may not assign to or increment. 在C中,预增量会导致rvalue表达式 ,您可能无法分配或递增。
It's not a logical problem; 这不是一个合乎逻辑的问题; it's a language problem.
这是一个语言问题。 You should split that complex formula into multiple code statements.
您应该将该复杂公式拆分为多个代码语句。
That's all there is to it. 这里的所有都是它的。
(In C++ it's an lvalue though and you can do both those things.) (在C ++中,它是一个左值 ,你可以做这两件事。)
In C, ++a
is not an l-value. 在C中,
++a
不是 l值。
Informally this means that you can't have it on the left hand side of an assignment. 非正式地,这意味着您不能将其放在作业的左侧。
It also means that you can't increment it. 这也意味着你不能增加它。
So (++a)++
is invalid code. 所以
(++a)++
是无效的代码。
(Note that it is valid C++). (注意它是有效的C ++)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.