Download presentation
Presentation is loading. Please wait.
Published byTommy Lye Modified over 9 years ago
1
Passing Arguments Suppose you’re seated in class, which doesn’t begin for another 20 minutes… …and your friend, who missed the last two classes due to emergency, asks to look at your workbook. You tell him, “Sure”, but instead of lending him your workbook, you run and make copies of the pages he needs. You do this to prevent him from making any changes to your workbook.
2
In the programming world, this situation mirrors Passing By Value. When an argument is passed by value to a function, this means the function will receive a copy of the original object. For example, suppose I create a function that computes the square of an argument: int square( int n ) { return n*n; } Square() is only interested in the value, not the original object. So we perform pass-by-value by giving only the type and the name, int n. The function then creates its own copy of the variable.
3
Now suppose it’s the next day in class, and your friend needs to take another look at your workbook. Class is only a minute away from starting, so you lend him your book this time. Upon getting it back, you notice a bunch of markings left in it by him.
4
This situation mirrors Passing by Reference. When an argument is passed by reference to a function, the function receives the original object, and thus can modify it. For example, suppose I have a function whose job is to swap values: void swap( int& m, int& n ) { int temp = m; m = n; n = temp; } In this case, Swap() needs the original variables to do its job. So I add a ‘ & ’ symbol to indicate ‘pass-by-reference’.
5
Now suppose it’s the last day of class, and your friend needs one last look at your workbook. You respond ‘OK’, but also mention that you did not appreciate the markings he left in it last time. He understands, and agrees to not leave any markings on it this time.
6
This situation mirrors Passing by Const-Reference, where ‘const’ is short for ‘constant’. This is done when you don’t want the argument to be modified, but you also don’t want to waste memory by creating a copy of it. For example, suppose I create a function that receives a Bank data structure as an argument: void printClients( const Bank& B ) { // Code goes in here } Assume this Bank object is very large in terms of memory. Passing it by value potentially causes a Core Dump, and passing it by reference leaves open the risk of it getting modified. So we kill two birds with one stone by passing it by const-reference.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.