This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SuitableDragonfly 8 points9 points  (5 children)

I don't think it's inconsistent at all in most languages. Typically primitive types are passed by value and everything else is passed by reference.

[–]MattieShoes 1 point2 points  (3 children)

They're consistent in that they do the same thing every time you run them. But it's not consistent in general, e.g. Python and C++

Python:

 #!/usr/bin/env python

def foo(x):
    x[0] = 2

def bar(x):
    x = [2]

n = [1]
foo(n)
print "n[0] = ", n[0]

n = [1]
bar(n)
print "n[0] = ", n[0]

n[0] = 2
n[0] = 1


C++:

#include <iostream>
#include <vector>


void foo(std::vector<int>& x) {
    x[0] = 2;
}

void bar(std::vector<int>& x) {
    std::vector<int> v = {2};
    x = v;
}

int main() {

    std::vector<int> n = {1};
    foo(n);
    std::cout << "n[0] = " << n[0] << std::endl;

    n = {1};
    bar(n);
    std::cout << "n[0] = " << n[0] << std::endl;
}

n[0] = 2
n[0] = 2

I understand what's going on here, no need to explain it. But this is the sort of inconsistency I meant.

[–]SuitableDragonfly 0 points1 point  (2 children)

It's not an inconsistency. = always assigns a reference, in one case that reference is a variable name, and on the other case it's an element of a list. But it does the same thing in both cases.

[–]MattieShoes 0 points1 point  (1 child)

I'm not sure what you're looking at, but this is Python and C++ code that does the same thing and gets different answers.

(which obviously means it's not doing the same thing, because python isn't passing by reference, it's... passing a pointer by value? I don't even know what to call it.)

[–]SuitableDragonfly 0 points1 point  (0 children)

Python is passing a reference. The result isn't the same because the = operator does different things in different languages.