C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Methods of Passing Arguments


You pass arguments from a function to another function in two ways: by value and by address. Both
of these methods pass arguments to a receiving function from a calling function. There is also a way
to return a value from a function back to the calling function (see the next chapter).


All this talk of passing values focuses on the parentheses that follow function names. That’s right,
those empty parentheses have a use after all! The variables you want to pass go inside the parentheses
of the function call and also in the receiving function, as you’ll see in the next section.


Note

Yes, this passing values stuff is important! It’s easy, though, as you’ll see.

Passing by Value


Sometimes passing by value is called passing by copy. You’ll hear these terms used interchangeably
because they mean the same thing. Passing by value means that the value of the variable is passed to
the receiving function, not the variable itself. Here is a program that passes a value from main() to
half():


Click here to view code image


// Example program #1 from Chapter 31 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter31ex1.c
/* The program demonstrates passing a variable to a function by
value. */
#include <stdio.h>
main()
{
int i;
printf("Please enter an integer... ");
scanf(" %d", &i);
// Now call the half function, passing the value of i
half(i);
// Shows that the function did not alter i's value
printf("In main(), i is still %d.\n", i);
return(0); // Ends the program
}
/******************************************************************/
/* Sometimes putting dividers like the one above is a nice break
between your different functions. */
Free download pdf