C++ modulo is not defined for floating-point operands: identify the outcome when using % with float values in a method.
#include
void Tester(float xx, float yy = 5.0); // unrelated free function
class CuriousTab
{
float x;
float y;
public:
void Tester(float xx, float yy = 5.0)
{
x = xx;
y = yy;
cout << ++x % --y; // invalid: % requires integral operands
}
};
int main()
{
CuriousTab objCuriousTab;
objCuriousTab.Tester(5.0, 5.0);
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 report compile time error.
Explanation
Introduction / Context: In C++, the % (remainder) operator is defined only for integral types. Attempting to apply it to floating-point operands is ill-formed. This snippet intentionally uses % with float values to provoke a compiler diagnostic.
Given Data / Assumptions:
- Method Tester takes float parameters and assigns to float members.
- Expression: ++x % --y with x and y of type float.
- Classic headers (iostream.h) do not affect the core language rule about %.
Concept / Approach: Both operands to % must be integral. Since ++x and --y are still floats, there is no valid operator% overload, and the code fails to compile with an error similar to “invalid operands to binary %”.
Step-by-Step Solution:
Set x = 5.0 and y = 5.0.Attempt to compute ++x % --y with float operands.Compiler rejects the expression at compile time; no program output is produced.Verification / Alternative check: Changing the members to int (and passing integer literals) would allow % and yield a value. Alternatively, use fmod from
Why Other Options Are Wrong:
- Any printed numeric output assumes successful compilation and execution, which does not occur.
- “Garbage value” implies runtime behavior; the failure is compile-time.
Common Pitfalls: Assuming % behaves like mathematical modulus for floats, or forgetting to use fmod for double/float types.
Final Answer: The program will report compile time error.