Passing information into functions in C - by name, by value
Archive - Originally posted on "The Horse's Mouth" - 2015-10-26 21:50:54 - Graham EllisIf you pass a variable into a function in C, you copy the contents into the function so thst any changes made internally in the function are not reflected in the main code copy. However, if you pass in the address of the variable and work at the same address inside and outside the function, any changes you make to the variable's contents within the function will be reflected in the calling code too. Example [here].
From that example - defining the function that uses a local copy of the value
void increase(int number) {
number++;
printf("Number is %d\n",number);
}
and calling that:
increase(people);
Alternative - defining the function that copies the address so that the variable is in effect aliased:
void boost(int *number) {
(*number)++;
printf("Number is %d\n",*number);
}
and calling that
boost(&people);
Neither approach is necessarily right - they work in different circumstances. But do note that calling by address is the sensible and effieicent way to pass large data structures (or, rather, references to them) around.
If you want to learn C of C++, we run courses - see [here] or get in touch leting us know your background and what you'll be doing with C or C++ so we can best advise.