Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

parameter difference between C++ and Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading