kmort
kmort

Reputation: 2928

Does modulus use floating point behind the scenes?

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

Answers (3)

user2864740
user2864740

Reputation: 61865

No1. Refer to some implementations of such an 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

twin
twin

Reputation: 1669

It's up to the implementation how "C++" calculates the modulus "behind the scenes"

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

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

Related Questions