See this page as a slide show
CS156 Reference: Passing Arguments by Reference
Passing by Reference instead of by value
- If we want a function to affect the variables in
the calling function, we can send the address of the variables.
- This is passing by reference instead of passing by value
- Remember the use of the
&
for scanf
,
to reference the address of a variable
&num
means “the address of num
”
Passing by Reference, not by value
/* Pass by value */
void doStuff(int val) {
val = 3;
}
int main( ) {
int x = 5;
doStuff(x);
printf("After, x=%d\n", x);
return 0;
}
After, x=5
/* Pass by reference */
void doStuff(int *val) {
*val = 3;
}
int main( ) {
int x = 5;
doStuff(&x);
printf("After, x=%d\n", x);
return 0;
}
After, x=3