Remainder after division by zero - c++

I know that division by zero is not allowed in math, but can I use modulo by zero and what answer should I get?
For example
10%0 = ?
5%0 = ?

The standard defines it as "undefined".
In nearly all processors, the modulo is performed by the same functionality as divide. In modern larger processors, it's an instruction (x86 for example). Most often, this instruction will cause a trap when dividing by zero, and this applies whether the code is "intending to use the modulo" or "quotient" part.
It is undefined so that processors and compilers have the freedom to implement what they fancy - e.g. if the processor just returns whatever came in as the input, that's also allowed, or if it causes the entire OS to crash, that's "fine" too by the standard.
In summary, modulo of zero is just as bad as divide by zero.
(Note that typically, floating point divide by zero does NOT trap [by default], and produces a infinity value, except if the value divided is also zero, in which case you get "not a number")

In C/C++ it is Undefined behaviour, you can get various of results depending on compiler or even different instances of same program.
C11dr §6.5.5
The binary / operator yields the quotient, and the binary % operator
yields the remainder from the division of the first expression by the
second. If the second operand of / or % is zero the behavior is
undefined

The result is UB
C11dr §6.5.5 "The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined."

Mathematically speaking you should get infinite, which is the correct answer... programmatically any sane compiler will warn you of division by zero as internally the modulo operator (at least in C/C++) is translated in a division (in most implementations). So the answer to your question is that you would get a floating point exception, in both cases.

Related

Does division operator ( / ) in C++ return the floor value in case of num with same sign and ceil value when both the numbers are of opposite sign?

In C++ , when both numerator and denominator are integers and of same sign , then division operator gives the floor value of the quotient . But when they are of opposite sign , then it gives ceil value . Is my understanding correct or is there more to it ?
You have it right. Some 20th-century hardware engineer decided to do it this way, and as far as I know this is how all microprocessors now natively do it. Mathematically, it's often a little inconvenient, which is why Python (for example) corrects in software always to round toward toward floor.
For additional insight, besides p/q for an integer quotient, try p%q for the corresponding remainder.
Your question is tagged C++ but this is really a computer hardware issue and, as such, it may be more helpful to consult the C17 standard, whose sect. 6.5.5(6) reads:
When integers are divided, the result of the / operator is the algebraic quotient with any fractional
part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a....
(I have a shred of a memory from 25 or 30 years ago, reading about a CPU that rounded toward floor. If my memory is not altogether imaginary, then that CPU apparently did not succeed in the marketplace, did it?)

Is maximum float + x defined behavior?

I did a quick test using the following:
float x = std::numeric_limits<float>::max();
x += 0.1;
that resulted in x == std::numeric_limits::max() so it didn't get any bigger than the limit.
Is this guaranteed behavior across compilers and platforms though? What about HLSL?
Is this guaranteed behavior across compilers and platforms though?
No, the behavior is undefined. The standard says (emphasis mine):
5 Expressions....
If during the evaluation of an expression, the result is not mathematically defined or not in the range of
representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++
ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all
floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]
As #user2079303 mentioned, in practice we can be less restricted:
it is not undefined if std::numeric_limits<float>::has_infinity. Which is often true. In that case, the result is merely unspecified.
The value of std::numeric_limits<T>::max() is defined to be the maximum finite value representable by type T (see 18.3.2.4 [numeric.limits.members] paragraph 4). Thus, the question actually becomes multiple subquestions:
Is it possible to create a value bigger than std::numeric_limits<T>::max(), i.e., is there an infinity?
If so, which value needs to be added to std::numeric_limits<T>::max() to get the infinity?
If not, is the behavior defined?
C++ does not specify the floating point format and different formats may disagree on what the result is. In particular, I don't think floating point formats need to define a value for infinity. For example, IBM Floating Points do not have an infinity. On the other hand the IEEE 754 does have an infinity representation.
Since overflow of arithmetic types may be undefined behavior (see 5 [expr] paragraph 4) and I don't see any exclusion for floating point types. Thus, the behavior would be undefined behavior if there is no infinity. At least, it can be tested whether a type does have an infinity (see 18.3.2.3 [numeric.limits] paragraph 35) in which case the operation can't overflow.
If there is an infinity I think adding any value to std::numeric_limits<T>::max() would get you infinity. However, determining whether that is, indeed, the case would require to dig through the respective floating point specification. I could imagine that IEEE 754 might ignore additions if the value is too small to be relevant as is the case for adding 0.1 to std::numeric_limits<T>::max(). I could also imagine that it decides that it always overflows to infinity.

Runtime error dividing by -1

I don't doubt the need to check for division by zero. I've never heard of checking for division by negative one though!
if( *y == 0 )
return 0; //undefined
else
return *x / *y;
x, y are pointers to int32_t, I include this detail in case of relevance.
At runtime, if *x==0x80000000, *y==0xffffffff, I get the error (in Xcode):
EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
All I can find online is suggestions that it is division by zero, but as you can see from the check above, and I can see from the debug window, that is not the case here.
What does the error mean, and how can I fix it?
2's complement representation is asymmetric: there is one more negative number than positive number, and that negative number has no positive counterpart. Consequently, negating MIN_INT is an integer overflow (where MIN_INT is the value whose only 1-bit is the sign bit, 0x80000000 for 32-bit integers).
MIN_INT / -1 is, therefore, also an arithmetic overflow. Unlike overflow from subtraction (which is rarely checked), overflow when dividing can cause a trap, and apparently that's what is happening in your case.
And, yes, technically speaking you should check for the MIN_INT / -1 overflow case before dividing, because the result is undefined.
Note: In the common case of Intel x64 architecture, division overflow does trap, exactly the same as division by 0. Confusingly, the corresponding Posix signal is SIGFPE which is normally thought of as "Floating Point Exception", although there is no floating point in sight. The current Posix standard actually glosses SIGFPE as meaning "Erroneous Arithmetic Operation".

A few things about division by zero in C [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Value returning 1.#INF000
I always thought division by 0 would result in a compiled program crashing
However I discovered today (using VC++ 2010 Express) that division by 0 gives something called 1.#INF000 and it is supposed to be positive infinity
When it was passed to a function, it got passed as -1.#IND000
What is this all about?
Searching 1.#INF000 and -1.#IND000 on google do not provide any clear explanations either
Is it just something specific to VC++ ?
Floating point division by zero behaves differently than integer division by zero.
The IEEE floating point standard differentiates between +inf and -inf, while integers cannot store infinity. Integer division by zero results in undefined behaviour. Floating point division by zero is defined by the floating point standard and results in +inf or -inf.
Edit:
As pointed out by Luchian, C++ implementations are not required to follow the IEEE Floating point standard. If the implementation you use doesn't follow the IEEE Floating point standard the result of floating point division by zero is undefined.
Edit: The question is about C++ and the result in C++ is undefined, as clearly stated by the standard, not the IEEE or whatever other entity that doesn't, in fact, regulate the C++ language. The standard does. C++ implementations might follow IEEE rules, but in this case it's clear the behavior is undefined.
I always thought division by 0 would result in a compiled program crashing
Nope, it results in undefined behavior. Anything can happen, a crash is not guaranteed.
According to the C++ Standard:
5.6 Multiplicative operators
4) The binary / operator yields the quotient, and the binary %
operator yields the remainder from the division of the first
expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b
is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is
implementation-defined79). (emphasis mine)
Quoting the latest draft of the ISO C++ standard, section 5.6 ([expr.mul]):
If the second operand of / or % is zero the behavior is undefined.
This applies to both integer and floating-point division.
A particular C++ implementation may conform to the IEEE floating-point standard, which has more specific requirements for division by zero, which which case the behavior may be well defined for that implementation. That's probably why floating-point division by zero yields Infinity in your implementation. But the C++ standard doesn't require IEEE floating-point behavior.
you can use the following code sniplet in C.
it throws the exception. it works on linux donno about windows though
#include <fenv.h>
#include <TRandom.h>
static void __attribute__ ((constructor)) trapfpe(void)
{
/* Enable some exceptions. At startup all exceptions are masked. */
feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);
}

Integer division rounding with negatives in C++

Suppose a and b are both of type int, and b is nonzero. Consider the result of performing a/b in the following cases:
a and b are both nonnegative.
a and b are both negative.
Exactly one of them is negative.
In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.
As an update to the other answers:
The last draft of C++11, n3242 which is for most practical purposes identical to the actual C++11 standard, says this in 5.6 point 4 (page 118):
For integral operands the / operator yields the algebraic quotient
with any fractional part discarded; (see note 80)
Note 80 states (note that notes are non-normative):
80) This is often called truncation towards zero.
Point 4 goes on to state:
if the quotient a/b is representable in the type of the result,
(a/b)*b + a%b is equal to a.
which can be shown to require the sign of a%b to be the same as the sign of a (when not zero).
According to the May 2008 revision,
You're right:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75).
Note 75 says:
According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.
Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it.
I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is.
Just a comment. The current working draft for the C++ standard indeed corrects the "implementation-defined" issue and asks for truncation towards zero. Here is the committee's webpage, and here is the draft. The issue is at page 112.
Sometimes we need to take a step back, and look just at the mathematics of it:
Given int x, int y
if int i1 = x/y and
int i2 = x%y
then y * i1 + i2 must be x
So this is not so much about the standard, but there is only one way this can possibly be. If any standards allows it to be any other way, then the standard is wrong, and that means the language is broken.