Pass by Value

One important thing about calling functions in C, and the main reason we need to learn about pointers so early, is that in C all functions pass their parameters by value. Let me show what it means, and how it is related to pointers!

Void functions

Before we go further, I'll spend a minute showing a type of function we haven't seen before: a function with no return value. Such a function does not have any result; when it's called, its code is executed and then it exits. Instead of writing

int f(/* parameters */) { 
	...
	return some_value;
}

for a function with no return value, we'll write

void f(/* parameters */) {
	...
}

If we need to return early from such function, we just say return; without giving it any value. We use void functions when we need them to do some work but there is no result that this function could reasonably return.

Parameters are passed by value

So, let's take a look at one specific example of a function. What do you think the code would print? Try to guess first, and then run the code to see if you are right.

#include <stdio.h>

void f(int x) {
	++x;
}

int main() {
	int a = 5;
	printf("before: %d\n", a);
	f(a);
	printf("after: %d\n", a);
	return 0;
}

You can see that even though the function f increments the value of its parameter x, it has no effect on a. This is because a is passed by value, which means that the value of a is copied into another place in memory (or elsewhere–it might be a CPU register) before it is passed to a function. A function can do whatever it wants with that value, it's never copied back.

If you think a little bit about it, it becomes pretty logical. You can call our function passing a constant as its int parameter:

f(42);

so if the function actually incremented the parameter it was called with, and not its copy, what would it do with the constant 42?

It is important to understand that all parameters are always passed by value in C. There is no way a function can change its parameter.

If you heard something about "references", that's C++ and is not applicable to plain C we are talking about here.

To learn how parameters are passed is an important question that we always try to figure out when we learn a new language, because each language has its own approach.

But if, for some reason, we need to change the parameter from inside a function, what do we do? Can we do it at all?

No problem! Instead of passing a value, we pass a pointer to that value. Easy! Let's see how it works on the next page.