paul23
paul23

Reputation: 9445

semantical reasons for pass-by-reference

I'm really wondering, is pass by reference (or passing a pointer) ever the "best" solution semantically wise? Especially for primitive types it feels like:

int x = 5;
x = foo(x);

is more natural than

int x = 5;
foo(x);

I first thought about code needing to return error codes, however then I realised using exception mechanisms is always(?) preferable over this. Are there real reasons why one would wish to pass by reference? - Leaving speed out of the scope for now.

Upvotes: 0

Views: 82

Answers (1)

Anthales
Anthales

Reputation: 1158

Arguably, for primitive types, it really is more natural to pass them by value. Just looking at mathematics, we all have an understanding of values and know what we mean by mapping values to other values.

For example when we write sin(x), we really want our function sin to map the value (of) x to another value which we simply denote sin(x). Sometimes we want to give the mapped value a different name, so we could write something like y := sin(x) and use y instead of sin(x).

Now if sin would take this parameter by-reference, sin(x) would mean, that the value of x would be mapped to sin(x) and implicitely stored in x again - so the old value of x would be lost!

In many cases this would be really annoying because we may want to use the "old" x again - so we would have to copy its value beforehand.

Now lets look at the other hand: OOP. There you want to have objects, like a car for example, and this object should be able to change. For example cars can move (if they have gas), therefore they can change their position; driving costs gas, so the gas tank will deplete over time; you can open the doors etc etc...

Here we don't think about mapping a car to another car (a copy) with its door opened or its gas tank slightly decreased, but we really think about the same car, but now with open doors.


So again in short:

  • passing by value is good when we want the arguments to not lose its original meaning - its most useful for mapping values.

  • passing by reference is good when we want our value (which we here interpret as an object) to change.


So semantically it is quite clear what you typically want to use pass by value/pass by reference for, but there are some problems one could have with passing by value:

If your object is a resource, then passing that resource by value would (probably) mean, that you`d allocate a second resource! This is sometimes simply not possible - e.g. think about (TCP) network connections. When you already have one, its not possible to open another on the same port, sharing the context in the already open connection. So in such cases you really have no choice but pass your network connection (socket, data stream, whatever) by reference.

Upvotes: 1

Related Questions