Functions :: The Problem
- So now you must be thinking... Wow! Functions are great! I can do anything with functions! WRONG. There are four major ways that parameters are passed into functions. The two that we should be concerned with are Pass by Value and Pass by Reference. In C, all parameters are passed by value.
- So you're saying so what? It makes a big difference. In simplistic terms, functions in C create copies of the passed in variables. These variables remain on the stack for the lifetime of the function and then are discarded, so they do not affect the inputs! This is important. Let's repeat it again. Passed in arguments will remain unchanged. Let's use this swapping function as an example:
void swap(int x, int y) {
int tmp = 0;
tmp = x;
x = y;
y = tmp;
}If you were to simply pass in parameters to this swapping function that swaps two integers, this would fail horribly. You'll just get the same values back. - But thankfully, you can circumvent this pass by value limitation in C by simulating pass by reference. Pass by reference changes the values that are passed in when the function exits. This isn't how C works technically but can be thought of in the same fashion. So how do you avoid pass by value side effects? By using pointers and in some cases using macros. We will discuss pointers in detail later.
Tags:
Functions :: The Problem