I am given a piece of code for which we have to guess output.
My Output: 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. So we are in 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.
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.
In C, pre-increment results in an rvalue expression, which you may not assign to or increment.
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.)
In C, ++a is not an l-value.
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.
(Note that it is valid C++).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With