Reputation: 2928
In C++ does a modulus use any floating point math behind the scenes?
int x = 1234;
int y = 5678;
int z = y % x; // any floating point used underneath to calculate the integer result?
As background, I was thinking about this question where he said he couldn't use any floating point without FP emulation. Then I realized that I wasn't sure if the modulus operator used any sort of floating point assembly operations. My guess is it does not, but I would like to be sure.
Upvotes: 1
Views: 317
Reputation: 61865
No1. Refer to some implementations of such an operator.
Assembly Language - How to Do Modulo? - "[In x86] the DIV instruction [..] gives both the quotient and remainder"
Assembly mod algorithm on processor with no division operator
1 An implementation can do whatever it wants insofar as the observed behavior is within the specification. However, I don't know of any implementation which would choose to use floating point operations, nor can I think of a general justification for doing so.
Upvotes: 3
Reputation: 1669
It's up to the implementation how "C++" calculates the modulus "behind the scenes"
Upvotes: 1
Reputation: 310910
No it does not use the floating point arithmetic. The result can be obtained very simply
z = y - ( y/x ) * x;
Early computers sometimes have no floating point coprocessor. So such operations are performed by using machine commands that operate with integer numbers.
Upvotes: 2