+ 5

C++ output - Who does explain me?

Why final values of b is 300, whilst a remains 200? It's like p=q assignment is left-to-right! #include <iostream> using namespace std; int main() { int a = 200, b = 100; int *p = &a, *q = &b; p = q; *p = 300; cout << b << a; return 0; }

30th Mar 2019, 7:44 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 Answers
+ 5
Because of line p = q p points to b too. That means that *p = 300 alters b, not a.
30th Mar 2019, 7:49 PM
Jan Štěch
Jan Štěch - avatar
+ 4
Tricky! Just take a breath and read the code.. *q=&b // pointer q is initialized with &b p=q // the address value in q(which is &b) is assigned to p Now p contains &b *p =300 // 300 is assigned to b trough p pointer.
1st Apr 2019, 12:16 PM
AZTECCO
AZTECCO - avatar
+ 4
When p=q was coded, p started pointing to b and then value was substituted in case of p. So tht means we changed b's value.
3rd Apr 2019, 3:07 AM
Suhani Goyal
Suhani Goyal - avatar