Suppose you’re writing a function to double a given number. You might naively assume that this would be a reasonable solution:
C
#include <stdio.h>
int doubleIt(int number) {
return number * 2;
}
int main(void) {
int number = 3;
doubleIt(number);
printf("Doubled number is %d", number);
return 0;
}
If you run it you’ll find number
remains unchanged. This is, you might be surprised to discover, by design. It’s down to C’s pass by value semantics.
Instead, use referential semantics as follows to allow the doubleIt
function to have access to the number
variable.
C
#include <stdio.h>
void doubleIt(int *number) {
*number *= 2;
}
int main(void) {
int number = 3;
doubleIt(&number);
printf("Doubled number is %d", number);
return 0;
}
If you run this you’ll find this function works as you would hope and does indeed double the number passed to it.