In C++ (iostream.h), a class method with default parameters modifies members and prints an expression using pre-increment and pre-decrement. Determine the output.
#include
void Tester(int xx, int yy = 5); // unrelated free function
class CuriousTab
{
int x;
int y;
public:
void Tester(int xx, int yy = 5)
{
x = xx;
y = yy;
cout << ++x % --y;
}
};
int main()
{
CuriousTab objCuriousTab;
objCuriousTab.Tester(5, 5);
return 0;
}
-
AThe program will print the output 0.
-
BThe program will print the output 1.
-
CThe program will print the output 2.
-
DThe program will print the output garbage value.
-
EThe program will report compile time error.
Answer
Correct Answer: The program will print the output 2.
Explanation
Introduction / Context: The problem focuses on default parameters and operator semantics in C++. It asks you to evaluate an expression that uses pre-increment and pre-decrement with integer operands and the modulo operator, all inside a class method invoked with explicit arguments.
Given Data / Assumptions:
- Method Tester(int, int = 5) is called as Tester(5, 5).
- Computation: cout << ++x % --y; with integer x and y.
- Free function Tester declared above is unrelated to the member call.
Concept / Approach: Pre-increment ++x yields 6. Pre-decrement --y yields 4. The modulo operation with integers computes 6 % 4, which equals 2. The method prints this result directly.
Step-by-Step Solution:
Initialize x = 5, y = 5 via parameters.Compute ++x → 6.Compute --y → 4.Compute 6 % 4 → 2; stream it to cout.Verification / Alternative check: Replacing pre- with post- (x++ % y--) would evaluate to 5 % 5 → 0 first, but the code explicitly uses pre-operators, so the printed result is 2.
Why Other Options Are Wrong:
- The program will print the output 0./1.: Do not match 6 % 4.
- The program will print the output garbage value.: All variables are well-defined.
- The program will report compile time error.: There is no ambiguity; member call resolves correctly.
Common Pitfalls: Confusing the free Tester declaration with the class method; mixing up pre- and post- increments which change the numeric result; overlooking that modulo is only valid for integral types (which we have here).
Final Answer: The program will print the output 2.