CPA-21-02 practice question 15 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; int op(int x, int y); int main() { float *pf; float f=0.9; pf=&f; cout

Full set: 257 questions
Answer options
A: It prints: 0 Correct answer
B: It prints: 0.5
C: It prints: 1
D: It prints: ?1
Correct Answer:
A. It prints: 0
Explanation

The variable f is initialized to 0.9, and the pointer pf points to f. When op(1, pf) is called, the dereferenced float value 0.9 is passed as the second argument. The function op expects an int for both parameters. C++ performs an implicit standard conversion (floating-integral conversion) from float to int. This conversion truncates the fractional part, converting 0.9 to 0. The function then returns 1 0, which evaluates to 0, and this value is printed to the standard output.

Why Incorrect

B: The function expects an int, so the float 0.9 is truncated to 0, not kept as a float. C: The float 0.9 is truncated towards zero to 0, not rounded up to 1. D: There is no logic or conversion in the code that would produce a negative result.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 7.10 [conv.fpint], Paragraph 1.

- Stroustrup, B. (2013). The C++ Programming Language (4th Ed.). Addison-Wesley. Chapter 10.5.

Scroll to Top