This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Pass by Value When an argument is passed to a function using the pass by value method, essentially a copy of the argument’s value is passed to the function. It is impossible for the function to modify the actual argument since it does not “know” the location of where this argument is stored in the memory, it only has a copy of the value that is stored in that location. copied Memory Figure 1. Configuration at the time Function X calls Function Y . Copy of actual parameter a is copied into location of formal parameter m . Figure 2. Configuration while Function Y is in execution. Assume Y changes the value of m. Figure 3. Configuration just after Function Y has completed execution. Modularity: Functions - 15 Modularity: Functions – Chapter 7 – Part 2 Calling function: X actual parameter: a Called function: Y formal parameter: m memory cell of a 27 memory cell of m 27 Calling function: X actual parameter: a Called function: Y formal parameter: m memory cell of a 27 Calling function: X actual parameter: a Called function: Y formal parameter: m memory cell of a 27 memory cell of m 19 P a s s b y V a l u e A n i l l u s t r a t i o n o f h o w t h e a c t u a l p a r a m e t e r i n t h e c a l l i n g f u n c t i o n i s u n c h a n g e d b y t h e a c t i o n s o f t h e c a l l e d f u n c t i o n . d o u b l e c l i c k i n t h i s w i n d o w t o s t a r t t h e s h o w Figure 4. PowerPoint slide shown illustrating pass-by-value. Parameters in the C language are passed by value. This restriction of the C language is in many ways an asset rather than a liability. It usually leads to more compact code that contains fewer extraneous variables, because the function arguments can be treated as conveniently initialized local variables in the called function. Pass by Reference Sometimes it is necessary to arrange for a called function to modify a variable in the calling function. This requirement means that the argument must be passed by reference. In order to achieve the effect of call-by-reference in C, we must use pointers in the formal parameter list in the function definition and pass addresses of variables as actual parameters in the function call. [As we will see later, this is the only way in which an array can be passed in C, i.e., it is not possible to pass an array by value in C.] You are already familiar with this technique as this is what we have been doing in the scanf( ) statements that we have been using in our programs to date. The function call scanf(“%d”, &alpha); causes an appropriate value to be stored at the address in memory which is identified by the identifier alpha . Recall that &alpha is the address, or location in memory of the variable alpha....
View Full Document
- Summer '09
- Computer Science