Skip to content
Advertisement

parameter difference between C++ and Python

C++

JavaScript

Python

JavaScript

I think their code should return same result however C ++ result is

JavaScript

Python result is

JavaScript

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.

JavaScript

The output of the above modified program is equivalent to the output produced from python:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement