Online Coding Lessons C and C++ Coding 2 — Questions and Answers
Question 1: In C, what does the sizeof operator return for an int on most modern 64-bit systems?
- 2 bytes
- 4 bytes (Correct answer)
- 8 bytes
- 1 byte
Correct answer: 4 bytes
An int is typically 4 bytes on most modern platforms regardless of 32- or 64-bit.
Question 2: Which C++ keyword is used to prevent a member function from modifying the object's state?
- static
- const (Correct answer)
- volatile
- mutable
Correct answer: const
Marking a member function const guarantees it will not modify the object's members.
Question 3: What is the result of the C expression 7 / 2 when both operands are integers?
- 3.5
- 3 (Correct answer)
- 4
- 3.0
Correct answer: 3
Integer division in C truncates the fractional part, yielding 3.
Question 4: In C++, which container provides automatic dynamic resizing and contiguous storage?
- std::list
- std::vector (Correct answer)
- std::map
- std::set
Correct answer: std::vector
std::vector stores elements contiguously and grows automatically as needed.
Question 5: What does the C standard library function malloc return when allocation fails?
- 0 as an int
- NULL (Correct answer)
- -1
- An uninitialized pointer
Correct answer: NULL
malloc returns NULL when it cannot allocate the requested memory.
Question 6: Which operator is used to access a struct member through a pointer in C?
- .
- -> (Correct answer)
- ::
- &
Correct answer: ->
The arrow operator -> dereferences a pointer and accesses the member in one step.
Question 7: In C++, what does the 'new' operator do that 'malloc' does not?
- Allocates on the stack
- Calls the object's constructor (Correct answer)
- Returns void*
- Never throws
Correct answer: Calls the object's constructor
new allocates memory and invokes the constructor, while malloc only allocates raw bytes.
In C, what does the sizeof operator return for an int on most modern 64-bit systems?