Download presentation
Presentation is loading. Please wait.
1
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 9: Pass-by-Value
2
Today We Are Going To: Discuss the concept of “pass-by-value” Discuss the concept of “pass-by-value” Complete our discussion of methods Complete our discussion of methods
3
Topic Pass-by-Value
4
Parameters C++ allows parameters to be passed in several ways C++ allows parameters to be passed in several ways by value by value by reference (called variable parameters) by reference (called variable parameters) by constant reference by constant reference
5
Concerns In practice, mixing value and variable parameters creates logic errors that are difficult to solve In practice, mixing value and variable parameters creates logic errors that are difficult to solve Value parameters are “safer” Value parameters are “safer” Also are slightly less efficient Also are slightly less efficient BE CLEAR on what is being passed; if the item is an array or object, or if it is a pointer, the effects can be surprising BE CLEAR on what is being passed; if the item is an array or object, or if it is a pointer, the effects can be surprising
6
Example #1 Write a simple program with a single defined method: Write a simple program with a single defined method: public static void swap(int inV1, int inV2) public static void swap(int inV1, int inV2) Code this method so that it causes the two input variables to change places Code this method so that it causes the two input variables to change places Write a main method which assigns values to them and prints those values before and after a swap is made Write a main method which assigns values to them and prints those values before and after a swap is made
7
Example #2 Now modify that program so that the method uses variable parameters: Now modify that program so that the method uses variable parameters: public static void swap(int& inV1, int& inV2) public static void swap(int& inV1, int& inV2) Repeat your test Repeat your test
8
Example #3 Now modify that program so that the method uses constant references: Now modify that program so that the method uses constant references: public static void public static void swap(const int& inV1, const int& inV2) Repeat your test Repeat your test
9
Today We Have: Specified the nature of parameter passing within C++ Specified the nature of parameter passing within C++ Concluded our discussion of methods Concluded our discussion of methods
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.