Important Introduction to Programming Short Questions
Chapter: 30
Question 1:
What happens if you increment a variable that has a reference?
Answer:
Incrementing a variable that has a reference will also increment the reference since both refer to the same memory location.
Chapter: 30
Question 2:
What is the main difference between references and pointers in C++?
Answer:
References are aliases for variables and cannot be null or reassigned, while pointers can point to different memory addresses and support pointer arithmetic.
Chapter: 30
Question 3:
Why can't a reference be NULL in C++?
Answer:
A reference must always be initialized to refer to an existing variable; hence, it cannot be NULL.
Chapter: 30
Question 4:
What happens if a function returns a reference to a local variable?
Answer:
Returning a reference to a local variable can cause a dangling reference because the local variable goes out of scope when the function ends.
Chapter: 30
Question 5:
How can you avoid a dangling reference when returning a reference from a function?
Answer:
To avoid a dangling reference, return references to global or static variables that persist throughout the program.
Chapter: 30
Question 6:
Can you overload a function that takes a reference and another that takes a value?
Answer:
No, overloading functions with one taking a reference and another taking a value is not allowed due to ambiguity in function calls.
Chapter: 30
Question 7:
Why is it dangerous to return a reference to a local variable?
Answer:
It's dangerous because the local variable's memory is deallocated when the function ends, leaving the reference pointing to invalid memory.
Chapter: 30
Question 8:
What is the benefit of using const with a reference parameter?
Answer:
Using const with a reference parameter prevents the function from modifying the original variable, ensuring the safety of the original data.
Chapter: 30
Question 9:
How does call by reference improve efficiency in C++?
Answer:
Call by reference avoids the overhead of copying large data structures by passing references instead of values, improving performance.
Chapter: 30
Question 10:
What does the & operator signify when used in a function prototype?
Answer:
In a function prototype, the & operator indicates that the function expects a reference to a variable rather than a value.