| C Tutorial | Swap example | |||
|
Introduction to functions in C Syntax Void functions Call by Value and call by reference Swap example Reference parameter technique Const Bigger pointer example
|
The classic example of wanting to modify the caller's memory is a swap() function which exchanges two values. Because C uses call by value, the following version of Swap will not work...
void Swap(int x, int y) { // NO does not work int temp;
temp = x; x = y; // these operations just change the local x,y,temp y = temp; // -- nothing connects them back to the caller's a,b }
// Some caller code which calls Swap()... int a = 1; int b = 2; Swap(a, b);
Swap() does not affect the arguments a and b in the caller. The function above only operates on the copies of a and b local to Swap() itself. This is a good example of how "local" memory such as ( x, y, temp) behaves -- it exists independent of everything else only while its owning function is running. When the owning function exits, its local memory disappears.
Want To Know more with Video ??? Contact for more learning: webmaster@freehost7com |
|