Online Coding Lessons C and C++ Coding 3 — Questions and Answers
Question 1: What is a dangling pointer in C?
- A pointer set to NULL
- A pointer to freed or out-of-scope memory (Correct answer)
- A pointer to a constant
- A pointer to an array
Correct answer: A pointer to freed or out-of-scope memory
A dangling pointer references memory that has been freed or has gone out of scope.
Question 2: In C++, which feature allows a function to operate on multiple types using a single definition?
- Inheritance
- Templates (Correct answer)
- Namespaces
- Overloading
Correct answer: Templates
Templates let you write generic code that works with any type.
Question 3: What does the 'static' keyword do for a local variable inside a C function?
- Makes it global
- Preserves its value between calls (Correct answer)
- Allocates it on the heap
- Makes it constant
Correct answer: Preserves its value between calls
A static local variable retains its value across multiple function calls.
Question 4: Which C++ smart pointer ensures exclusive ownership of a resource?
- std::shared_ptr
- std::unique_ptr (Correct answer)
- std::weak_ptr
- std::auto_ptr
Correct answer: std::unique_ptr
std::unique_ptr enforces sole ownership and cannot be copied.
Question 5: What is the output type of the C comparison expression (5 > 3)?
- A boolean true
- An int with value 1 (Correct answer)
- A char
- A float
Correct answer: An int with value 1
In C, relational expressions evaluate to an int, 1 for true and 0 for false.
Question 6: In C++, what is the purpose of a destructor?
- Initialize members
- Clean up resources when an object is destroyed (Correct answer)
- Copy an object
- Compare two objects
Correct answer: Clean up resources when an object is destroyed
A destructor releases resources and runs automatically when an object goes out of scope.
Question 7: What does the preprocessor directive #include do in C?
- Compiles a file
- Inserts the contents of another file (Correct answer)
- Defines a macro
- Links a library at runtime
Correct answer: Inserts the contents of another file
#include textually inserts the named header's contents before compilation.
What is a dangling pointer in C?