2

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++

4
  • 2
    Because in python, we pass an object reference instead of the actual object. 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. Commented May 29, 2022 at 8:37
  • In c++, x is the variable declared in main, while y is the function input parameter variable. So, indeed, x and y actually doesn't have the same address, then &x and &y does not points to the same location. Commented May 29, 2022 at 8:40
  • 1
    @Sedenion No, x is not a global variable. It is a local variable in function main. Commented May 29, 2022 at 8:41
  • @AnoopRana you right, language abuse, my bad. Commented May 29, 2022 at 8:42

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.