+ 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
7 odpowiedzi
+ 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
+ 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
+ 1
but then why is ++p =p working??
+ 1
There, he explained better.
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!
0
thanks...that really helped!!
- 3
court<<p<<;