1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <iostream> using namespace std; // Function to update even number to upper nearest odd using pass-by-value void updateToUpperOddByValue(int num) { if (num % 2 == 0) { num += 1; cout << "Inside updateToUpperOddByValue: " << num << endl; } } // Function to update even number to upper nearest odd using pass-by-reference void updateToUpperOddByReference(int &num) { if (num % 2 == 0) { num += 1; cout << "Inside updateToUpperOddByReference: " << num << endl; } } int main() { int x = 8; // Update using pass-by-value cout << "Before updateToUpperOddByValue: " << x << endl; updateToUpperOddByValue(x); cout << "After updateToUpperOddByValue: " << x << endl; // Update using pass-by-reference cout << "Before updateToUpperOddByReference: " << x << endl; updateToUpperOddByReference(x); cout << "After updateToUpperOddByReference: " << x << endl; return 0; } |
Explanation
- updateToUpperOddByValue Function:
- This function takes an integer as a parameter by value.
- It checks if the number is even (i.e., divisible by 2), and if so, it increments the number by 1 to make it odd.
- Since the function uses pass-by-value, changes made inside the function do not affect the original variable.
- updateToUpperOddByReference Function:
- This function takes an integer as a parameter by reference.
- It checks if the number is even, and if so, it increments the number by 1 to make it odd.
- Since the function uses pass-by-reference, changes made inside the function directly affect the original variable.
Output
1 2 3 4 5 6 7 | Before updateToUpperOddByValue: 8 Inside updateToUpperOddByValue: 9 After updateToUpperOddByValue: 8 Before updateToUpperOddByReference: 8 Inside updateToUpperOddByReference: 9 After updateToUpperOddByReference: 9 |
Key Points
- Pass-by-Value: The original value of
x
remains unchanged after the function call. - Pass-by-Reference: The original value of
x
is updated to the nearest upper odd number after the function call.