Unlike modern programming language, C has always been mysterious to even the most experienced of developers.
There’s always some feature of C that will surprise you even when you’re sure you know it inside out.
This is because C was written during a time when men were men and wrote their own operating systems in machine language.
So it was quite common for the creator of the language to put in quirks that made sense only to him. No one back then thought computers
would become common place.
So when the digital era kicked it, UNIX and C were behind its success, pushing it even further.
And C has faithfully carried forward these quirks to this date and I’m surprised every time I discover one.
Here’s an hypothetical, an interviewer tells you “C has only pass-by-value” , how would you support his argument?
It’s your first interview, and you’re already Stephen mcSweaty-Pants and he throws you this bouncer.
Consider the following code snippet
void foo ( int * bar, int * baz)
You show this code to him and point to the header, pointers!!
you will be passing references to integer variables, surely this is pass-by-reference?
He still insists that C has only pass-by-value, you now think that he’s gone mad and that you probably won’t land this job.
Then he tells you consider how you would call the function
foo( &x, & y);
Now take a long look at that second line.
“Yeah, I’m passing references to x and y as required”
True, but try elaborating it a bit more (no puns intended)
“You are passing the VALUES of the memory address at which the values are stored”
To elaborate, the memory addresses of the actual parameters are copied onto the locations pointed to by the formal parameters
and and then the evaluation occurs.
So even when you’re passing references, you’re passing values of the addresses, which is effectively pass-by-value 🙂
Question: So how would you pass by reference in any language?
Turns out, Pascal supports pass by reference by using the var keyword.
procedure swap ( var x: integer, var y : integer);
var z : integer;
z :=x; x:=y; y:=z;
In Pascal, a formal parameter becomes a synonym for the location of an actual parameter.
keyword var is used to indicate this.
Inspired by and Pascal code snippet from “Programming Languages : concepts & constructs, Second edition” by Ravi Sethi