In order to aect the actual value of arguments a and

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: le in the calling funcCon. Example: swap(a,b); /* will not swap */ … void swap(int x, int y){ int temp; temp = x; x = y; y = temp; } 8 Pointers and Func/on Arguments (cont’d) • The call by value cannot affect the value of the arguments a and b because the funcCon only swaps copies of a and b. • In order to affect the actual value of arguments a and b when using the swap funcCon, we must pass pointers to the values. swap(&a, &b); • This is called passing by reference because we are passing the address of the actual variable. 9 Pointers and Func/on Arguments (cont’d) void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; in caller (main): a: b: } in swap: px: py: 10 Why Pass by Reference? • Some reasons why variables are passed by reference: – Rather than returning a single value and assigning it to a variable, we can instead manipulate the variable contents directly by using its address. – It is o_en more intuiCve to calculate and return the value of several variables together. • One example of needing to return several values together is the vector operaCon of addiCon. 11 Passing by Reference Example • Vectors may be specified by using a triple (x, y, z). • In C, we can use an array to represent each vector: double v1[3] = {1, 2, 3}, v2[3] = {-1, 2, -3}, v...
View Full Document

This document was uploaded on 03/10/2014 for the course ENGINEER 2sh4 at McMaster University.

Ask a homework question - tutors are online