why this code doesn't work?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why this code doesn't work??

#include <iostream> using namespace std; int main() { int p = 10; p++ = p; cout<<p; return 0; } // whereas the following works #include <iostream> using namespace std; int main() { int p = 10; ++p = p; cout<<p; return 0; } // please answer

12th Aug 2016, 12:34 AM
kamal joshi
kamal joshi - avatar
7 Answers
+ 3
the reason why the first code doesn't work is due to how it gets parsed. when you say p++, what you're saying is make a copy of p, increment it, then set p = the new value. when a compiler reads p++=p it would be reading the increment operator as what's being set to the value of p, which is why you get an lvalue error. the reason the later code works I'd because ++p=p tells the compiler to increment the next variable it finds, which is p. now before we've hit the = operator, p has had 1 added to its value then just sets itself equal to itself. which is 11
12th Aug 2016, 8:15 PM
destro
+ 2
Because of p++ = p, it should just be p++; alone, saying p++ is the same as p = p + 1, or p += 1. Hope this helps! Also it will just print 11 then quit because of return 0
12th Aug 2016, 3:49 AM
Jed Gould
Jed Gould - avatar
+ 1
but then why is ++p =p working??
12th Aug 2016, 11:52 AM
kamal joshi
kamal joshi - avatar
+ 1
There, he explained better.
12th Aug 2016, 10:51 PM
Jed Gould
Jed Gould - avatar
0
I don't know, but all I is p++ means increment p after this line, and ++p means increment p before this line. So my theory is that the = p in ++p = p doesn't actually do anything, because ++p is not a variable, so all it does is increments p and ignores = p. p++ doesn't work because p is called to increment after already giving it a value, so this causes an error. That is just my theory, so im not 100 % sure. Hope this helped!
12th Aug 2016, 12:16 PM
Jed Gould
Jed Gould - avatar
0
thanks...that really helped!!
13th Aug 2016, 3:03 AM
kamal joshi
kamal joshi - avatar
- 3
court<<p<<;
12th Aug 2016, 2:29 AM
Wahidullah Ahmady
Wahidullah Ahmady - avatar