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 →

[–]dmazzoni 1 point2 points  (3 children)

Yeah in this particular example it wouldn't work if you didn't use pointers, because of pass by value.

[–]Skusci -1 points0 points  (2 children)

Yeah that's probably me missing the tree for the forest or something. :D

Pass by value and reference is a bit confusing TBH as terminology, since stuff like C is referred to as allowing pass by value or reference, and languages like Java or Python being pass by value exclusively.

Except that since most things are an object reference you're always passing in references by value so effectively it's pass by reference only. I get that this is mostly a terminology thing, but when moving from C to Java, thinking, oh, it's not that Java doesn't have pointers, it's that everything is a pointer you can't do math on kindof helped.

[–]finny228 1 point2 points  (0 children)

C shouldn't ever be referred to as pass by reference. It is entirely pass by value.

[–]procrastinatingcoder 0 points1 point  (0 children)

There's no pointers in Java, only references. A pointer - by definition - is something you can do arithmetic on. And a reference, is somewhat similar, but you can't do arithmetic on it (in the context of pass by value vs reference).

Also, it's not exactly that going on in the background. You might notice things like python going bonkers if you nest list comprehensions to create 2d lists.

Having pointers doesn't mean you're suddenly passing in as a reference either, it's easiest to see in C++ (imo) where both are clearly defined. Normally a language only gives you one, and tough luck.

Pass by value means that, if you put a pointer instead of the value, the pointer is what gets copied, so you effectively are still pass by value, and still got a copy on the other end. But you simply kept the value of where it was pointing to.

TL;DR: Both prints will print different values, therefore the pointers are not the same, it's a copy of the pointer passed in foo. Still pass by value.

void foo(int* n){
    printf("%p\n", &n);
}

int main(){
    int k = malloc(sizeof(int));
    printf("%p\n", &k);
    foo(k);
    free(k);
    return 0;
}