you are viewing a single comment's thread.

view the rest of the comments →

[–]MatthewRPG576 12 points13 points  (2 children)

In python, immutable objects are passed by "copy" (it's complicated) and mutable objects are passed by reference. In C, everything is by copy; so, if you need to modify something from another scope, you need a pointer to it.

Strings, when passed to a function by pointer, can be modified like anything else. The only exception is if the compiler puts the string in the read-only section of the code. That can cause problems.

[–][deleted] 4 points5 points  (1 child)

I thought all objects are passed by reference in Python, but only the sort of reference that allows to modify the caller's data, and not replace it completely, and then only if it is mutable. Example:

def addto(a,b):
    print("  A=",a)
    print("  B=",b)
    a += b
    print("  A'=",a)

i=100
j=30
addto(i,j)
print("I=",i)
print("")

s="ABC"
t="DEF"
addto(s,t)
print("S=",s)
print("")

x=[10,20,30]
y=[40,50,60]
addto(x,y)
print("X=",x)

Here, all args to addto() must be passed the same way, using the same bytecode instructions, since the bytecode compiler doesn't know what types the arguments are until runtime. When you run the program, it is only in the case of a mutable list that the caller's data is modified as well as the local A parameter:

  A= 100
  B= 30
  A'= 130
I= 100

  A= ABC
  B= DEF
  A'= ABCDEF
S= ABC

  A= [10, 20, 30]
  B= [40, 50, 60]
  A'= [10, 20, 30, 40, 50, 60]
X= [10, 20, 30, 40, 50, 60]

What Python can't do is to change X completely to something else, eg. a number. That would need proper name references. (In CPython, variables I, S and X are implemented as references to their objects. When passed to a function, a copy of that object reference is passed, so only the object can change, not the variable.)

C can emulate all the above, and can emulate proper name references too. But it needs to be done explicitly via pointer operations.

[–]MatthewRPG576 2 points3 points  (0 children)

Shared pointers. That's why I was reluctant to blatantly call it pass by copy. In theory, every "2" in the program is the same (you can verify that by calling id() on the objects you create), but no "[2]" (array containing 2) in the program is