0

#include <iostream> using namespace std; int main() { int x=10,y=20; int *ptr = &x; int &ref= y; *ptr++; ref++; cout<<x<<y

please explain the code and its output in detail..

4th Jul 2017, 8:26 AM
Kushagra Agarwal
Kushagra Agarwal - avatar
9 odpowiedzi
+ 1
https://code.sololearn.com/cCDCJ5MCdCTe/?ref=app If you want more informations ask !
4th Jul 2017, 9:11 AM
Jojo
0
Do you know and UNDERSTAND pointers ? 😇
4th Jul 2017, 8:35 AM
Jojo
0
Yes but i couldn't understand this code
4th Jul 2017, 8:49 AM
Kushagra Agarwal
Kushagra Agarwal - avatar
0
Do you know parameters by reference (int &) ? Look at this piece of code : void function(int &a, &b){} int main(){ int c, d; function (c, d); } When 'function(c, d)' is executed, that's like : int &a=c, &b=d and then, every changes on 'function' apply on 'a' or 'b' is also apply on 'c' and 'd'. If you still don't understand ask ! I'm going to post à code to explain.
4th Jul 2017, 9:05 AM
Jojo
0
The output of your code is 1021. Why not 1121??
4th Jul 2017, 11:52 AM
Kushagra Agarwal
Kushagra Agarwal - avatar
0
Because the priority is to the increment: *ptr++; // == *(ptr++); So it's the value if the POINTER wich is incremented, not the value of 'x'. But if you write this : (*ptr)++; // The value of 'x'is incremented. If you want more informations ask
4th Jul 2017, 12:10 PM
Jojo
0
I've modified the code take a look
4th Jul 2017, 12:14 PM
Jojo
0
#include <iostream> using namespace std; void function(int &ref){ ref++; } int main() { int x=10,y=20; int *ptr=&x; (*ptr)++; function(y); cout << x << y << endl; cout << *ptr << " " << ptr << endl; *ptr++; cout << x << " " << ptr; return 0; } I have changed *ptr to x (2nd last line) which also changes the output. But these both mean the same thing. Don't they?
4th Jul 2017, 12:18 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
0
Well.. you've understood. However, when '*ptr++;' is written, remember it is like '*(ptr++);' so, in this case like 'ptr++;'. ptr++; increments ptr's value wich is an ADRESS (x's address). Once this value incremented, it is ANOTHER ADRESS. So ptr points on another variable in the memory. And *ptr != x anymore because ptr != &x
5th Jul 2017, 10:18 AM
Jojo