CPA-21-02 practice question 17 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; void set(struct person*); struct person { int age; }; int main() { struct person e = {18}; set(&e); coutage = p?>age + 1; }

Full set: 257 questions
Answer options
A: It prints: 18
B: It prints: 19 Correct answer
C: It prints: 20
D: It prints: 0
Correct Answer:
B. It prints: 19
Explanation

The program defines a person struct and initializes an instance e with an age of 18. The set function takes a pointer to a person struct. By passing the address of e (&e) to set, the function receives a pointer that allows it to modify the original object in memory. Inside set, the arrow operator (->, represented as ?> due to a typographical artifact in the prompt) is used to access and increment the age member by 1. Thus, e.age becomes 19, which is subsequently printed.

Why Incorrect

A: Incorrect because the set function receives a pointer to the struct, allowing it to successfully modify the original age value in memory. C: Incorrect because the age is only incremented by 1 (from 18 to 19), not by 2. D: Incorrect because the age is explicitly initialized to 18 and incremented; it is never set or reset to 0.

References

1. ISO/IEC 14882:2014 (C++14 Standard), Section 5.2.5 "Class member access" (use of the arrow operator).

2. ISO/IEC 14882:2014 (C++14 Standard), Section 8.3.1 "Pointers".

3. Stanford University, CS106B Programming Abstractions, Lecture on Pointers and Structs.

Scroll to Top