4 ms·
Yes, you can do that in C, but that is still not pass by reference. In C you are not passing the variable you are trying to change, you are passing a pointer t
by ta82828 12y ago
Yes, you can do that in C, but that is still not pass by reference. In C you are not passing the variable you are trying to change, you are passing a pointer to it. You cannot write
swap(a, b);
You have to write
swap(&a, &b);
- lucio 12y agoThe problem is that you will label both cases as an example of "pass-by-value", while they're fundamentally different. That's why people call "pass-by-reference" the second example.
- TazeTSchnitzel 12y agoThey're not fundamentally different. The passing semantics are the same in both cases, the variable bound within the body of swap will not be the same variables we are passing it. The difference is that the value being passed is a pointer in the second case.
- ta82828 12y agoThey are both labelled pass-by-value because they are both pass-by-value. Yes, they are different, but that doesn't mean one is pass-by-reference and the other is pass-by-value. The C example is equivalent to pa = &a; pb = &b; swap(pa, pb); When swap returns, the values of pa and pb are unchanged. Only the values or a and b are changed. But a and b were not passed to swap. Therefore this is not pass-by-reference, but rather passing a pointer to a variable by value.
- lucio 12y agoI fully understand the difference, and I know that you're technically correct. What I'm saying is that people tend to abbreviate "pass-a-reference-by-value" to "pass-by-reference" because the differences between passing a value (value snapshot) and passing a reference-value (passing the address-of) are way more important* than if the language syntax allows you to pass an "implicit" variable reference or not. (the swap example) *"more important" for code-reading, code-analysis, code-safety analysis, and also even more important in a concurrent environment because of side-effects and data-races. Maybe the feature should be called "pass an implicit reference", which describes better what Java does, instead of saying "everything is pass-by-value" which is correct but, as the evidence shows (the mere existence of the article), it is very confusing for "folks". >I'm really tired of hearing folks (incorrectly) state "primitives are passed by value, objects are passed by reference".
- deleted 12y ago[deleted]