Lecture Notes Of Class 14: Functions - Pass by Reference
Lecture Notes Of Class 14: Functions -
Pass by Reference
Objective:
In this class, we will
learn about passing data by reference in functions. We will explore how
this concept works, especially in programming languages that allow the
manipulation of variables through references. We will also cover the concept of
pointers and how they are used in passing variables by reference.
Introduction to Passing
Data in Functions:
When we call a function
and pass data to it, the data can be passed in two main ways:
1.
Pass by Value
2.
Pass by Reference
1. Pass by Value:
- Pass
by Value means that a copy of the actual
argument is passed to the function.
- In
this case, any changes made to the parameter inside the function do not
affect the original value.
- Example
in C++:
cpp
CopyEdit
void modifyValue(int x) {
x = 10;
// Changes made to 'x' inside the function don't affect the original
'x'.
}
int main() {
int a = 5;
modifyValue(a);
cout << "Value of a: "
<< a; // Output will be 5, as the
original value of 'a' is not changed.
return 0;
}
2. Pass by Reference:
- Pass
by Reference means that instead of passing a copy
of the variable, the actual memory address of the variable is
passed.
- This
allows the function to modify the original value, as it works with the
variable's reference (or address) directly.
- In
C/C++ programming, this is accomplished using pointers.
Pass by Reference Using
Pointers
A pointer is a
variable that stores the memory address of another variable. By passing the
pointer to a function, we allow the function to access and modify the original
variable using its memory address.
Basic Syntax:
To pass a parameter by
reference using pointers, you need to:
1.
Declare the parameter as a pointer in the
function definition.
2.
Pass the address of the variable (using &
operator) when calling the function.
Example 1: Pass by
Reference Using Pointers
cpp
CopyEdit
#include <iostream>
using namespace std;
// Function that takes a
pointer to an integer (pass by reference)
void modifyValue(int
*ptr) {
*ptr = 10;
// Dereferencing the pointer to modify the value of the original
variable.
}
int main() {
int a = 5;
cout << "Before function call:
" << a << endl; //
Output will be 5
modifyValue(&a); // Passing the address of 'a' to the function
cout << "After function call:
" << a << endl; //
Output will be 10, as the original 'a' is modified
return 0;
}
Explanation of the Code:
1.
Function Definition:
The modifyValue function takes a pointer int *ptr. This means the function
expects the address of an integer as its argument.
2.
Dereferencing the Pointer:
Inside the function, *ptr is used to dereference the pointer. Dereferencing
means accessing the value stored at the address the pointer points to. By
setting *ptr = 10;, we modify the value of the original variable passed from main().
3.
Passing the Address:
In main(), we pass the address of variable a using the & operator: modifyValue(&a);.
This allows the function to modify a directly.
4.
Effect:
After the function call, the value of a in main() has changed to 10 because we
passed its address and modified its value via the pointer.
Why Use Pass by
Reference?
Advantages of Passing by
Reference:
1.
Efficient Memory Usage:
o When
passing large data (like large arrays or structures), passing by reference is
more memory-efficient than passing by value because it avoids copying the
entire data structure.
2.
Ability to Modify the Original Data:
o With
pass by reference, any changes made inside the function are reflected outside
the function, which is useful when you need to update variables without
returning them.
3.
Reduces Overhead:
o Pass
by reference can improve performance by reducing the overhead of copying large
objects.
Example 2: Modifying
Multiple Variables
cpp
CopyEdit
#include <iostream>
using namespace std;
void modifyValues(int *a,
int *b) {
*a = 100;
// Modify the first variable
*b = 200;
// Modify the second variable
}
int main() {
int num1 = 10, num2 = 20;
cout << "Before function call:
num1 = " << num1 << ", num2 = " << num2
<< endl;
modifyValues(&num1, &num2); // Pass the addresses of num1 and num2
cout << "After function call:
num1 = " << num1 << ", num2 = " << num2
<< endl;
return 0;
}
Output:
r
CopyEdit
Before function call:
num1 = 10, num2 = 20
After function call: num1
= 100, num2 = 200
In this example, both num1
and num2 are modified inside the function by passing their memory addresses.
Conclusion:
- Passing
by Reference is a powerful technique that allows
you to modify the actual variables in the calling function. This is done
by passing pointers (memory addresses) of the variables to the function.
- It
is commonly used to modify large data structures or when you need to
return multiple values from a function without using arrays or structures.
- In
languages like C++, pointers allow efficient memory management and direct
manipulation of data, which is important in large-scale programs.
By using pointers and
passing by reference, you gain more control over your program's data, enabling
more efficient and powerful coding practices.
Key Points to Remember:
1.
Pointers
store the memory address of a variable.
2.
Dereferencing
a pointer means accessing the value stored at the memory address it points to.
3.
Pass by Reference
allows a function to modify the original value of a variable, while Pass by
Value creates a copy of the data, leaving the original unchanged.
4.
Use pass by reference for large
data structures or when you need to modify the actual data.
Practice Problems:
1.
Write a program that swaps two numbers
using pass by reference.
2.
Create a function that takes an array and
modifies its values using pass by reference.
This concludes our class
on Pass by Reference. Do practice using pointers and passing data by
reference to understand the concepts better!
4o mini
You said:
Write 10 assignments with
solution , detail explanation and output in detail on above concept
ChatGPT said:
ChatGPT
Below are 10 assignments
focused on the Pass by Reference concept using Pointers in C++
programming. Each assignment includes a detailed explanation, the solution, and
the expected output.
Assignment 1: Modify a
Variable Using Pass by Reference
Problem:
Write a program that takes an integer as input and modifies its value inside a
function using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void modifyValue(int
*ptr) {
*ptr = 50;
// Modify the original value of the variable
}
int main() {
int num = 10;
cout << "Before modification:
" << num << endl;
modifyValue(&num); // Pass the address of num
cout << "After modification:
" << num << endl;
return 0;
}
Explanation:
- modifyValue
function takes a pointer to int (int *ptr), which allows modification of
the original variable passed to it.
- *ptr
is used to access and modify the value stored at the memory address of the
variable.
Output:
mathematica
CopyEdit
Before modification: 10
After modification: 50
Assignment 2: Swapping
Two Numbers Using Pass by Reference
Problem:
Write a program to swap two numbers using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void swapNumbers(int *a, int
*b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 5, num2 = 10;
cout << "Before swap: num1 =
" << num1 << ", num2 = " << num2 <<
endl;
swapNumbers(&num1, &num2); // Pass addresses of num1 and num2
cout << "After swap: num1 =
" << num1 << ", num2 = " << num2 <<
endl;
return 0;
}
Explanation:
- We
use the temporary variable temp to swap the values stored at the addresses
of num1 and num2.
- &num1
and &num2 pass the addresses of the variables to the function.
Output:
mathematica
CopyEdit
Before swap: num1 = 5, num2
= 10
After swap: num1 = 10, num2
= 5
Assignment 3: Adding Two
Numbers Using Pass by Reference
Problem:
Write a program to add two numbers and return the result through the parameters
using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void addNumbers(int *a, int
*b, int *result) {
*result = *a + *b; // Sum of the two numbers is stored in result
}
int main() {
int num1 = 8, num2 = 12, sum = 0;
addNumbers(&num1, &num2,
&sum); // Pass addresses of num1,
num2, and sum
cout << "Sum: " <<
sum << endl;
return 0;
}
Explanation:
- The
function addNumbers computes the sum of num1 and num2 and stores the
result in the sum variable.
- The
address of sum is passed to store the result.
Output:
makefile
CopyEdit
Sum: 20
Assignment 4: Modifying
Multiple Variables Using Pass by Reference
Problem:
Write a program to modify two variables inside a function using pass by
reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void modifyValues(int *a,
int *b) {
*a = 100;
*b = 200;
}
int main() {
int num1 = 10, num2 = 20;
cout << "Before modification:
num1 = " << num1 << ", num2 = " << num2
<< endl;
modifyValues(&num1, &num2); // Pass addresses of num1 and num2
cout << "After modification:
num1 = " << num1 << ", num2 = " << num2
<< endl;
return 0;
}
Explanation:
- The
function modifyValues changes the values of both num1 and num2 by
dereferencing the pointers.
- The
addresses of num1 and num2 are passed to the function.
Output:
mathematica
CopyEdit
Before modification: num1
= 10, num2 = 20
After modification: num1 =
100, num2 = 200
Assignment 5:
Incrementing Array Elements Using Pass by Reference
Problem:
Write a program to increment each element of an array using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void incrementArray(int
*arr, int size) {
for(int i = 0; i < size; i++) {
arr[i]++; // Increment each element in the array
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Before increment:
";
for(int i = 0; i < size; i++) {
cout << arr[i] << "
";
}
cout << endl;
incrementArray(arr, size); // Pass the array to the function
cout << "After increment: ";
for(int i = 0; i < size; i++) {
cout << arr[i] << "
";
}
cout << endl;
return 0;
}
Explanation:
- The
function incrementArray takes the address of the array and increments each
element by 1.
- The
array is passed by reference to allow modifications to its elements.
Output:
mathematica
CopyEdit
Before increment: 1 2 3 4
5
After increment: 2 3 4 5 6
Assignment 6: Swapping
Three Numbers Using Pass by Reference
Problem:
Write a program to swap three numbers using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void swapThreeNumbers(int
*a, int *b, int *c) {
int temp = *a;
*a = *b;
*b = *c;
*c = temp;
}
int main() {
int num1 = 1, num2 = 2, num3 = 3;
cout << "Before swap: num1 =
" << num1 << ", num2 = " << num2 << ",
num3 = " << num3 << endl;
swapThreeNumbers(&num1, &num2,
&num3); // Pass the addresses of
num1, num2, and num3
cout << "After swap: num1 =
" << num1 << ", num2 = " << num2 << ",
num3 = " << num3 << endl;
return 0;
}
Explanation:
- The
function swapThreeNumbers swaps the values of three variables using a
temporary variable.
- It
takes pointers to all three variables to modify their values directly.
Output:
mathematica
CopyEdit
Before swap: num1 = 1, num2
= 2, num3 = 3
After swap: num1 = 2, num2
= 3, num3 = 1
Assignment 7: Finding the
Maximum and Minimum Using Pass by Reference
Problem:
Write a program to find the maximum and minimum of two numbers using pass by
reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void findMaxMin(int *a, int
*b, int *max, int *min) {
if (*a > *b) {
*max = *a;
*min = *b;
} else {
*max = *b;
*min = *a;
}
}
int main() {
int num1 = 15, num2 = 25, max, min;
findMaxMin(&num1, &num2, &max,
&min); // Pass addresses of num1,
num2, max, and min
cout << "Max: " <<
max << ", Min: " << min << endl;
return 0;
}
Explanation:
- The
function findMaxMin compares two numbers and stores the maximum and
minimum values in the max and min variables.
Output:
mathematica
CopyEdit
Max: 25, Min: 15
Assignment 8: Calculating
the Average of Array Elements Using Pass by Reference
Problem:
Write a program to calculate the average of an array using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void calculateAverage(int
*arr, int size, float *avg) {
int sum = 0;
for(int i = 0; i < size; i++) {
sum += arr[i];
}
*avg = (float)sum / size;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
float avg;
calculateAverage(arr, size, &avg); // Pass the array and the address of avg
cout << "Average: "
<< avg << endl;
return 0;
}
Explanation:
- The
function calculateAverage computes the sum of the array elements and
calculates the average, which is stored in avg.
Output:
makefile
CopyEdit
Average: 30
Assignment 9: Checking
for Even or Odd Numbers Using Pass by Reference
Problem:
Write a program to check if a number is even or odd using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void checkEvenOdd(int
*num, string *result) {
if (*num % 2 == 0) {
*result = "Even";
} else {
*result = "Odd";
}
}
int main() {
int number = 27;
string result;
checkEvenOdd(&number,
&result); // Pass the address of
number and result
cout << "The number is "
<< result << endl;
return 0;
}
Explanation:
- The
function checkEvenOdd checks if a number is even or odd by using the
modulus operator and stores the result as a string.
Output:
csharp
CopyEdit
The number is Odd
Assignment 10: Modifying
a String Using Pass by Reference
Problem:
Write a program to modify a string using pass by reference.
Solution:
cpp
CopyEdit
#include <iostream>
using namespace std;
void modifyString(char
*str) {
str[0] = 'H'; // Modify the first character of the string
}
int main() {
char str[] = "hello";
cout << "Before modification:
" << str << endl;
modifyString(str); // Pass the string
cout << "After modification:
" << str << endl;
return 0;
}
Explanation:
- The
function modifyString changes the first character of the string by
accessing the string via a pointer.
Output:
mathematica
CopyEdit
Before modification: hello
After modification: Hello
These assignments will
help students understand the concept of pass by reference in C++ using
pointers and how they can modify variables directly in functions.
4o mini
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
Here are 50 Multiple
Choice Questions (MCQs) on the concept of Pass by Reference using
Pointers in C++. Each question includes an explanation of the correct
answer.
1. What is the main
advantage of using pass by reference in a function?
a) It copies the value of
the argument to the function
b) It allows modification of the original argument passed to the function
c) It prevents changes to the argument
d) It does not use memory for passing arguments
Answer:
b) It allows modification of the original argument passed to the function
Explanation: Pass by reference allows the function to modify the
original argument by passing its memory address (pointer) instead of making a
copy.
2. Which of the following
is used to pass an argument by reference in C++?
a) * (asterisk)
b) & (ampersand)
c) : (colon)
d) => (arrow)
Answer:
b) & (ampersand)
Explanation: The ampersand (&) is used in the function definition to
pass parameters by reference. It indicates that the argument is passed by
reference.
3. In the pass by
reference method, the function receives the address of the argument. What
keyword is used in the function declaration to accept the reference?
a) &
b) *
c) address
d) reference
Answer:
a) &
Explanation: The & symbol is used to declare a reference parameter
in a function, allowing the function to modify the original argument.
4. What is the output of
the following code?
cpp
CopyEdit
#include <iostream>
using namespace std;
void modifyValue(int
&x) {
x = 100;
}
int main() {
int num = 50;
modifyValue(num);
cout << num;
return 0;
}
a) 50
b) 100
c) Compilation error
d) Runtime error
Answer:
b) 100
Explanation: The function modifyValue changes the value of num directly
because x is passed by reference.
5. How does pass by
reference differ from pass by value in C++?
a) In pass by reference,
the function can modify the original variable.
b) Pass by value always modifies the original variable.
c) Pass by reference creates a copy of the variable in the function.
d) Pass by reference does not use memory for variables.
Answer:
a) In pass by reference, the function can modify the original variable.
Explanation: Pass by reference passes the memory address, allowing the
function to modify the original variable, whereas pass by value creates a copy
of the variable in the function.
6. What will be the
output of the following code?
cpp
CopyEdit
#include <iostream>
using namespace std;
void swap(int &a, int
&b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
cout << x << " "
<< y;
return 0;
}
a) 5 10
b) 10 5
c) Compilation error
d) Runtime error
Answer:
b) 10 5
Explanation: The function swap modifies x and y directly by reference,
swapping their values.
7. Which of the following
is the correct syntax to pass an integer by reference in C++?
a) int *x
b) int &x
c) int x&
d) &int x
Answer:
b) int &x
Explanation: The correct syntax to declare a reference parameter is int
&x, where & signifies that the argument is passed by reference.
8. Which operator is used
to dereference a pointer in C++?
a) &
b) *
c) ->
d) ::
Answer:
b) *
Explanation: The * operator is used to dereference a pointer, meaning it
accesses the value at the address the pointer is pointing to.
9. What will happen if a
pointer is passed by reference instead of by value?
a) The function can
modify the pointer itself
b) The function can modify the value pointed to by the pointer
c) The pointer will be reset to NULL
d) It will cause a segmentation fault
Answer:
a) The function can modify the pointer itself
Explanation: When a pointer is passed by reference, the function can
modify the pointer (the address it holds), not just the value it points to.
10. What is the output of
the following code?
cpp
CopyEdit
#include <iostream>
using namespace std;
void modify(int *ptr) {
*ptr = 200;
}
int main() {
int num = 150;
modify(&num);
cout << num;
return 0;
}
a) 150
b) 200
c) Compilation error
d) Runtime error
Answer:
b) 200
Explanation: The pointer ptr receives the address of num, and through
dereferencing (*ptr), it modifies the value of num to 200.
11. Which type of
argument passing is commonly used when large data structures, like arrays, are
passed to functions?
a) Pass by reference
b) Pass by value
c) Pass by pointer
d) Pass by constant
Answer:
a) Pass by reference
Explanation: Pass by reference is commonly used for large data
structures because it avoids copying the entire structure, improving
performance.
12. How can you change
the value of a variable in the calling function in C++?
a) By passing the
variable by value
b) By passing the variable by reference
c) By returning the new value
d) By using global variables
Answer:
b) By passing the variable by reference
Explanation: Passing by reference allows the called function to modify
the original variable in the calling function.
13. What will the
following code print?
cpp
CopyEdit
#include <iostream>
using namespace std;
void setValues(int
&a, int &b) {
a = 50;
b = 100;
}
int main() {
int x = 10, y = 20;
setValues(x, y);
cout << x << " "
<< y;
return 0;
}
a) 10 20
b) 50 100
c) Compilation error
d) Runtime error
Answer:
b) 50 100
Explanation: The function setValues modifies x and y directly because
they are passed by reference.
14. In the following
code, what will num be after the function call?
cpp
CopyEdit
#include <iostream>
using namespace std;
void addValue(int
&num) {
num += 10;
}
int main() {
int num = 25;
addValue(num);
cout << num;
return 0;
}
a) 25
b) 35
c) 15
d) Compilation error
Answer:
b) 35
Explanation: The function addValue increments num by 10. Since num is
passed by reference, the change is reflected in the main function.
15. Which of the
following statements is true regarding the pass by reference?
a) The function works
with a copy of the variable.
b) The function can modify the original variable.
c) It is not suitable for large objects.
d) It does not use memory for passing variables.
Answer:
b) The function can modify the original variable.
Explanation: In pass by reference, the function can directly modify the
original variable by using its memory address.
16. What will the
following program output?
cpp
CopyEdit
#include <iostream>
using namespace std;
void update(int *p) {
*p = 300;
}
int main() {
int x = 150;
update(&x);
cout << x;
return 0;
}
a) 150
b) 300
c) Compilation error
d) Runtime error
Answer:
b) 300
Explanation: The pointer p receives the address of x, and its value is
updated to 300 inside the function.
17. When passing an array
to a function in C++, what is passed by default?
a) The value of the array
b) The address of the first element of the array
c) A copy of the entire array
d) The size of the array
Answer:
b) The address of the first element of the array
Explanation: In C++, when passing an array to a function, what is
actually passed is the address of the first element, not the entire array.
18. What will happen if a
pointer is dereferenced incorrectly?
a) It will modify the
original variable
b) It will lead to a segmentation fault
c) It will print the address of the variable
d) It will cause a runtime error
Answer:
b) It will lead to a segmentation fault
Explanation: Dereferencing an invalid pointer or a NULL pointer results
in a segmentation fault, as it attempts to access a memory location that is not
allowed.
19. Which of the
following is true about the & symbol in C++?
a) It is used for
declaring a pointer.
b) It is used to pass arguments by value.
c) It is used to declare a reference variable.
d) It is used to dereference a pointer.
Answer:
c) It is used to declare a reference variable.
Explanation: The & symbol is used to declare a reference to a
variable, allowing the function to modify the original variable.
20. What will the
following code output?
cpp
CopyEdit
#include <iostream>
using namespace std;
void multiply(int &x,
int &y) {
x *= 2;
y *= 2;
}
int main() {
int a = 3, b = 4;
multiply(a, b);
cout << a << " "
<< b;
return 0;
}
a) 3 4
b) 6 8
c) 3 6
d) 8 8
Answer:
b) 6 8
Explanation: The function multiply multiplies both a and b by 2, and
since both are passed by reference, their values are updated.
I can continue the
remaining MCQs in another response to complete the set. Would you like to
proceed with that?
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Here is the continuation
of the MCQs:
21. What will the
following code print?
cpp
CopyEdit
#include <iostream>
using namespace std;
void updateValue(int
&a) {
a += 5;
}
int main() {
int num = 10;
updateValue(num);
cout << num;
return 0;
}
a) 10
b) 15
c) 5
d) Compilation error
Answer:
b) 15
Explanation: The function updateValue modifies the value of num by
adding 5, and since num is passed by reference, the updated value is reflected
in the main function.
22. Which of the
following is the correct syntax for passing a pointer by reference to a
function in C++?
a) void func(int &p)
b) void func(int *p)
c) void func(int &*p)
d) void func(int p*)
Answer:
b) void func(int *p)
Explanation: A pointer is passed by reference by using the syntax int *p,
where *p indicates a pointer, and p is passed by reference.
23. Which of the
following is NOT true about pass by reference in C++?
a) The original value of
the variable can be changed.
b) The function can modify the argument passed.
c) The function receives a copy of the variable.
d) Pass by reference uses the address of the argument.
Answer:
c) The function receives a copy of the variable.
Explanation: In pass by reference, the function receives the address of
the original variable, not a copy.
24. Which of the
following statements is correct about pointers in C++?
a) A pointer stores the
actual value of a variable.
b) A pointer stores the memory address of a variable.
c) A pointer can only be used with arrays.
d) A pointer automatically dereferences the value.
Answer:
b) A pointer stores the memory address of a variable.
Explanation: Pointers store the memory address of a variable, and they
are used to indirectly access and modify the value at that address.
25. What will the
following code output?
cpp
CopyEdit
#include <iostream>
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
swap(&a, &b);
cout << a << " "
<< b;
return 0;
}
a) 10 20
b) 20 10
c) 10 10
d) 20 20
Answer:
b) 20 10
Explanation: The swap function swaps the values of a and b. Since
pointers are used, the original values are swapped.
26. How does pass by
reference benefit large data structures like arrays and classes?
a) It reduces memory
usage by avoiding copies.
b) It makes the code slower.
c) It is only used with arrays.
d) It increases memory usage by making copies.
Answer:
a) It reduces memory usage by avoiding copies.
Explanation: Passing large data structures by reference avoids creating
copies of the entire structure, saving memory and improving performance.
27. What will happen if a
function is called by reference but an attempt is made to pass a constant
value?
a) Compilation error
b) The function will be executed but cannot modify the constant value
c) Runtime error
d) The constant value will be modified anyway
Answer:
a) Compilation error
Explanation: Passing a constant value by reference is not allowed in C++
because constants cannot be modified, and passing them by reference would allow
modification.
28. Which function is
best suited for modifying multiple variables in C++?
a) Functions with
pass-by-reference arguments
b) Functions with pass-by-value arguments
c) Functions using return values
d) Functions with global variables
Answer:
a) Functions with pass-by-reference arguments
Explanation: Pass-by-reference allows modifying multiple variables
directly inside the function.
29. What will the
following code output?
cpp
CopyEdit
#include <iostream>
using namespace std;
void modify(int &a) {
a = a * 2;
}
int main() {
int x = 4;
modify(x);
cout << x;
return 0;
}
a) 4
b) 8
c) 2
d) 16
Answer:
b) 8
Explanation: The function modify multiplies x by 2, so the output will
be 8.
30. What does the &
symbol represent when used in a function argument in C++?
a) It represents a
pointer
b) It represents pass by reference
c) It represents pass by value
d) It represents an address
Answer:
b) It represents pass by reference
Explanation: The & symbol in a function argument is used to pass the
argument by reference, allowing the function to modify the original variable.
31. What will be the
output of the following program?
cpp
CopyEdit
#include <iostream>
using namespace std;
void increment(int *x) {
(*x)++;
}
int main() {
int a = 7;
increment(&a);
cout << a;
return 0;
}
a) 7
b) 8
c) 9
d) Compilation error
Answer:
b) 8
Explanation: The pointer x points to a, and the value of a is
incremented inside the function, so the output is 8.
32. Which of the
following is correct about a reference variable in C++?
a) A reference variable
can be null.
b) A reference variable is a constant.
c) A reference variable must be initialized when declared.
d) A reference variable is not used to modify the argument.
Answer:
c) A reference variable must be initialized when declared.
Explanation: A reference variable must always be initialized when it is
declared and cannot be reassigned to refer to another variable.
33. How is memory managed
when passing a large data structure by reference?
a) It avoids memory
overhead because no copy is made.
b) It creates a separate copy of the data structure in memory.
c) It frees the memory used by the original data structure.
d) It causes a memory leak.
Answer:
a) It avoids memory overhead because no copy is made.
Explanation: Pass-by-reference avoids the overhead of copying large data
structures, thus improving efficiency.
34. What will be the
output of the following code?
cpp
CopyEdit
#include <iostream>
using namespace std;
void changeValue(int
&x) {
x += 5;
}
int main() {
int num = 20;
changeValue(num);
cout << num;
return 0;
}
a) 15
b) 20
c) 25
d) Compilation error
Answer:
c) 25
Explanation: The function changeValue modifies num by adding 5, and
since num is passed by reference, the new value is 25.
35. Which of the
following is true for a pointer passed by reference?
a) The function can
modify both the pointer and the value it points to.
b) The function can modify only the value it points to.
c) The pointer value cannot be modified.
d) The pointer value cannot be passed by reference.
Answer:
a) The function can modify both the pointer and the value it points to.
Explanation: Passing a pointer by reference allows modifying both the
pointer itself and the value it points to inside the function.
36. In the pass by
reference method, which of the following is passed to the function?
a) The value of the
argument
b) The address of the argument
c) A copy of the argument
d) A constant reference
Answer:
b) The address of the argument
Explanation: In pass by reference, the memory address of the original
argument is passed to the function, allowing it to modify the argument
directly.
37. What will the
following code print?
cpp
CopyEdit
#include <iostream>
using namespace std;
void change(int &a) {
a = 100;
}
int main() {
int x = 50;
change(x);
cout << x;
return 0;
}
a) 50
b) 100
c) 150
d) Compilation error
Answer:
b) 100
Explanation: The function change modifies x directly by reference,
setting its value to 100.
38. What will the
following program print?
cpp
CopyEdit
#include <iostream>
using namespace std;
void multiply(int &x,
int &y) {
x *= 2;
y *= 2;
}
int main() {
int a = 5, b = 10;
multiply(a, b);
cout << a << " "
<< b;
return 0;
}
a) 5 10
b) 10 20
c) 10 10
d) 10 15
Answer:
b) 10 20
Explanation: Both a and b are modified inside the function multiply by
multiplying them by 2. Since both are passed by reference, the changes are
reflected in the main function.
39. What is the primary
benefit of pass-by-reference?
a) Faster execution
b) Less memory usage
c) The original variable can be modified
d) It guarantees no side effects
Answer:
c) The original variable can be modified
Explanation: The primary benefit of pass-by-reference is that the
original argument can be modified within the function.
40. What happens when you
pass a constant variable by reference to a function?
a) It causes a
compile-time error because constants cannot be modified.
b) The constant value can be modified inside the function.
c) The value of the constant cannot be modified inside the function.
d) The constant value becomes a reference to another variable.
Answer:
a) It causes a compile-time error because constants cannot be modified.
Explanation: Constant variables cannot be modified, so passing them by
reference would violate that rule and result in a compile-time error.
Would you like me to
continue with the rest of the MCQs or need any further assistance?
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Here is the continuation
of the remaining MCQs:
41. Which of the
following is true about a reference in C++?
a) A reference must be
declared at the time of declaration and cannot be reassigned.
b) A reference can be reassigned after initialization.
c) A reference can be null.
d) A reference can point to multiple variables at once.
Answer:
a) A reference must be declared at the time of declaration and cannot be
reassigned.
Explanation: A reference in C++ must be initialized when declared and
cannot be changed to refer to another variable later.
42. What is the correct
way to declare a reference to a pointer in C++?
a) int &*p;
b) int *&p;
c) int &p*;
d) int p&*;
Answer:
b) int *&p;
Explanation: The correct syntax for declaring a reference to a pointer
is int *&p;, which allows the pointer to be modified and referenced.
43. What happens when you
use a reference as a function parameter?
a) A copy of the argument
is passed.
b) The original argument can be modified within the function.
c) Only the value of the argument is passed.
d) The reference is discarded after the function call.
Answer:
b) The original argument can be modified within the function.
Explanation: Using a reference allows the function to modify the
original argument passed to it.
44. Which of the
following is true about a pointer passed by reference?
a) The pointer itself can
be modified, but not the value it points to.
b) The pointer and the value it points to can both be modified.
c) The pointer can be used only to access the value it points to.
d) A pointer passed by reference has no effect on the original pointer.
Answer:
b) The pointer and the value it points to can both be modified.
Explanation: When a pointer is passed by reference, the function can
modify both the pointer itself (to point to a different address) and the value
at that address.
45. What will happen if
you try to dereference a pointer that has not been initialized?
a) It will cause a
runtime error.
b) It will point to a random memory location.
c) It will return a zero value.
d) It will compile successfully.
Answer:
b) It will point to a random memory location.
Explanation: Dereferencing an uninitialized pointer results in undefined
behavior, often leading to accessing random memory.
46. What is the major
advantage of passing large objects by reference in C++?
a) It decreases memory
usage because the object is not copied.
b) It makes the code more readable.
c) It increases memory usage due to copying.
d) It reduces the complexity of the program.
Answer:
a) It decreases memory usage because the object is not copied.
Explanation: Passing large objects by reference avoids the overhead of
copying the entire object, saving both time and memory.
47. What will the
following code print?
cpp
CopyEdit
#include <iostream>
using namespace std;
void setValue(int &a)
{
a = 42;
}
int main() {
int x = 5;
setValue(x);
cout << x;
return 0;
}
a) 5
b) 42
c) 0
d) Compilation error
Answer:
b) 42
Explanation: The function setValue modifies x to 42 because x is passed
by reference.
48. Which of the
following statements is true about pass-by-reference in C++?
a) Pass-by-reference is
always slower than pass-by-value.
b) In pass-by-reference, the memory address of the variable is passed to the
function.
c) Pass-by-reference creates a copy of the variable in the function.
d) Pass-by-reference is not used in C++.
Answer:
b) In pass-by-reference, the memory address of the variable is passed to the
function.
Explanation: In pass-by-reference, the function receives the address of
the original variable, allowing it to modify the original value.
49. What will be the
output of the following code?
cpp
CopyEdit
#include <iostream>
using namespace std;
void updateValue(int
*&ptr) {
*ptr = 100;
}
int main() {
int a = 10;
int *p = &a;
updateValue(p);
cout << *p;
return 0;
}
a) 10
b) 100
c) 0
d) Compilation error
Answer:
b) 100
Explanation: The pointer p is passed by reference to updateValue, where
the value it points to is modified to 100.
50. Which of the
following is an advantage of passing by reference in C++?
a) Pass-by-reference is
always faster than pass-by-value.
b) Pass-by-reference avoids copying the argument, saving memory.
c) Pass-by-reference ensures that the original value cannot be modified.
d) Pass-by-reference prevents side effects in the function.
Answer:
b) Pass-by-reference avoids copying the argument, saving memory.
Explanation: The key advantage of pass-by-reference is that it avoids
creating a copy of the argument, saving both memory and execution time.
These MCQs cover the key
concepts of passing by reference in C++, ensuring a solid understanding of the
topic. If you need more questions or further clarification, feel free to ask!
Comments
Post a Comment