假设我尝试执行以下操作:
y = 0;
z = x % y;
这个语义是定义明确的、平台相关的还是未定义的?我主要询问 C/C++,但对各种编程/脚本语言(Java、perl、sh 等)的答案很感兴趣
C 的行为是未定义的。
来自C11 6.5.5 乘法运算符,p5
/ 运算符的结果是第一个操作数除以第二个操作数的商;% 运算符的结果是余数。在这两种操作中,如果第二个操作数的值为零,则行为未定义。
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.
在 Java 中,如果您尝试编译
public static void main(String[] args) {
int x = 10,y,z;
y = 0;
z = x % y;
System.out.println("Z: " + z);
}
您将收到此消息:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at locationConfiguration.LocationConfigurator.main
因此,您将无法进行模零。