C++
#include <iostream> using namespace std; void doSomething(int y) { cout << y << " "<< & y << endl; } int main() { int x(0); cout << x << " " << & x << endl; doSomething(x); return 0; }
Python
def doSomething(y): print(y, id(y)) x = 0 print(x, id(x)) doSomething(x)
I think their code should return same result however C ++ result is
0 00000016C3F5FB14 0 00000016C3F5FAF0
Python result is
0 1676853313744 0 1676853313744
i don’t understand why variable’s address isn’t changed in Python while variable’s address is changed in C++
Advertisement
Answer
i don’t understand why variable’s address isn’t changed in Python while variable’s address is changed in C++.
Because in python, we pass an object reference instead of the actual object.
While in your C++ program we’re passing x
by value. This means the function doSomething
has a separate copy of the argument that was passed and since it has a separate copy their addresses differ as expected.
It is possible to make the C++ program produce the equivalent output as the python program as described below. Demo
If you change the function declaration of doSomething
to void doSomething(int& y)
you will see that now you get the same result as python. In the modified program below, i’ve changed the parameter to be an int&
instead of just int
.
//------------------v---->pass object by reference void doSomething(int& y) { cout << y << " "<< & y << endl; } int main() { int x(0); cout << x << " " << & x << endl; doSomething(x); return 0; }
The output of the above modified program is equivalent to the output produced from python:
0 0x7ffce169c814 0 0x7ffce169c814