Domanda

Suppose I try to perform the following:

y = 0;
z = x % y;

is the semantic for this well-defined, platform-dependent, or undefined? I'm asking mainly about C/C++, but am interested in the answer for various programming/scripting languages (Java, perl, sh, etc.)

I'm asking partly because there are different possible ways to define the modulo operation: As the remainder of a division operation; as the size of a quotient group, etc.

È stato utile?

Soluzione

Behaviour is undefined for C.

From C11 6.5.5 Multiplicative operators, p5

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.

Altri suggerimenti

It's well defined for JavaScript:

The result of an ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic: [...]

If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.


Now about the other languages. The common approach (Java, C#, Python, Ruby) is to throw some kind of ZeroDivisionError at you when you attempt to evaluate somenum % 0 expression.

For Perl, it's a bit more interesting:

use Data::Dumper;
print Dumper 0 % 0;
print 'Something else';

Now, this code results in Illegal modulus zero error; but had you put 0 / 0 instead, you would have seen Illegal division by zero message. Both are errors (stop execution of the remaining code), of course, not warnings.


Now PHP chooses a bit different stance on this:

var_dump(0 % 0); // it's the same for any numeric dividend
// Warning: Division by zero in ...
// bool(false)

As you see, you get false (sic) as a result, but warning is triggered. It's ignorable, though; have you set error_reporting level to E_ERROR, you wouldn't have even seen it.

in Java, if you try to compile

public static void main(String[] args) {
    int x = 10,y,z;
    y = 0;
    z = x % y;
    System.out.println("Z: " + z);
} 

You will get this message:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at locationConfiguration.LocationConfigurator.main

so, you won't be able to do modulo zero.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top