Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C not offer syntactically transparent references like C++ and Java do?

I tried to learn more about the historical reason[s] for passing by value in C. There is a Stack Overflow post that touches on this topic in relation to C++. However, I'm interested in C. I imagine back when this decision was made, one could have opted to do what we call now "pass by reference". Yet, this was not the choice made. Are there optimization, multi-threading, etc., issues that come into play?

I tried to Google this, but didn't get anywhere. Passing by value presents some guarantees in relation to the variable not being changed under the hood. Is this the only reason? I imagine back then the concept of "copying a fat object" wasn't much of an issue and passing by value incurred small overhead. As such, this might have been deemed the right choice. Is there more to this decision than this?

like image 285
Dan Avatar asked Nov 28 '22 16:11

Dan


2 Answers

In the words of Kernighan and Ritchie in The C Programming Language, 1978, clause 1.8 “Arguments — Call by Value,” page 24:

Call by value is an asset, however, not a liability. It usually leads to more compact programs with fewer extraneous variables, because arguments can be treated as conveniently initialized local variables in the called routine. For example,…

… When necessary, it is possible to arrange for a function to modify a variable in a calling routine. The caller must provide the address of the variable to be set (technically a pointer to the variable),…

like image 142
Eric Postpischil Avatar answered Dec 16 '22 03:12

Eric Postpischil


  1. Passing by value is often faster than passing by reference and dereferencing a pointer every time you want to use an argument. As structures were not a part of early C, and then later required to be passed as a pointer, this was not a big problem.

  2. Many old compilers didn't or couldn't optimize dereferences, and dereferencing a pointer every time you wanted to use an argument would be very slow.

  3. Old computers needed micro-optimized code to run faster because the processors themselves weren't very fast.

  4. It gives the programmer the freedom to choose whether they want to use a pointer or a value to access data.

All that together probably amounts to why C uses pass-by-value.

like image 39
S.S. Anne Avatar answered Dec 16 '22 04:12

S.S. Anne