Why is X % 0
an invalid expression?
I always thought X % 0
should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?
Why is X % 0
an invalid expression?
I always thought X % 0
should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?
you can evade the "divivion by 0" case of (A%B) for its type float identity mod(a,b) for float(B)=b=0.0 , that is undefined, or defined differently between any 2 implementations, to avoid logic errors (hard crashes) in favor of arithmetic errors...
by computing
mod([a*b],[b])==b*(a-floor(a))
INSTREAD OF
computing
mod([a],[b])
where [a*b]==your x-axis, over time [b] == the maximum of the seesaw curve (that will never be reached) == the first derivative of the seesaw function
https://www.shadertoy.com/view/MslfW8
X % Y gives a result in the integer [ 0, Y ) range. X % 0 would have to give a result greater or equal to zero, and less than zero.
X % D
is by definition a number0 <= R < D
, such that there existsQ
so thatSo if
D = 0
, no such number can exists (because0 <= R < 0
)The C++ Standard(2003) says in §5.6/4,
That is, following expressions invoke undefined-behavior(UB):
Note also that
-5 % 2
is NOT equal to-(5 % 2)
(as Petar seems to suggest in his comment to his answer). It's implementation-defined. The spec says (§5.6/4),I think because to get the remainder of
X % 0
you need to first calculateX / 0
which yields infinity, and trying to calculate the remainder of infinity is not really possible.However, the best solution in line with your thinking would be to do something like this
Another way that might be conceptually easy to understand the issue:
Ignoring for the moment the issue of argument sign,
a % b
could easily be re-written asa - ((a / b) * b)
. The expressiona / b
is undefined ifb
is zero, so in that case the overall expression must be too.In the end, modulus is effectively a divisive operation, so if
a / b
is undefined, it's not unreasonable to expecta % b
to be as well.