除数为零:未定义行为或实施在C和/或C ++中定义? [英] Division by zero: Undefined Behavior or Implementation Defined in C and/or C++?

查看:234
本文介绍了除数为零:未定义行为或实施在C和/或C ++中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于被零除,标准说:

C99 6.5.5p5 - /运算的结果是从由第二所述第一操作数的除法的商; %操作的结果是余数。在这两个操作,如果第二操作数的值是零,其行为是未定义

C99 6.5.5p5 - 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.

C ++ 03 5.6.4 - 二进制/运营商产生的商,和二元运算符%收益率从第二个第一八佰伴pression的余数。如果/或%第二个操作数为零,则行为未定义。

C++03 5.6.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.

如果我们把上面的段落面值,答案显然是未定义行为的两种语言。但是,如果我们在C99标准看进一步下跌,我们看到这似乎是矛盾的下列第(1):

If we were to take the above paragraphs at face value, the answer is clearly Undefined Behavior for both languages. However, if we look further down in the C99 standard we see the following paragraph which appears to be contradictory(1):

C99 7.12p4 - 宏INFINITY展开为float类型重新presenting正面或无符号无穷大的恒定前pression(如有);

C99 7.12p4 - The macro INFINITY expands to a constant expression of type float representing positive or unsigned infinity, if available;

执行标准有某种的金科玉律的在那里未定义行为不能由一个(潜在)矛盾的陈述所取代?除了上述,我不认为这是不合理的结论是,如果您的实现定义了INFINITY宏,被零除被定义为这样的。但是,如果您实现不执行的的定义这样一个宏,其行为是不确定的。

Do the standards have some sort of golden rule where Undefined Behavior cannot be superseded by a (potentially) contradictory statement? Barring that, I don't think it's unreasonable to conclude that if your implementation defines the INFINITY macro, division by zero is defined to be such. However, if your implementation does not define such a macro, the behavior is Undefined.

我很好奇的共识是什么(如果有的话),在这个问题上的每个两种语言。将答案改变,如果我们谈论的是整数除法 INT I = 1/0 与浮点除法浮法I = 1.0 / 0.0

I'm curious what the consensus is (if any) on this matter for each of the two languages. Would the answer change if we are talking about integer division int i = 1 / 0 versus floating point division float i = 1.0 / 0.0 ?

注意(1)关于C ++ 03标准的会谈< CMATH方式> 库其中包括INFINITY宏

Note (1) The C++03 standard talks about the <cmath> library which includes the INFINITY macro.

推荐答案

我看不出有任何矛盾。除数为零未定义,期限。没有的提......除非INFINITY定义的在引用文本的任何地方。

I don't see any contradiction. Division by zero is undefined, period. There is no mention of "... unless INFINITY is defined" anywhere in the quoted text.

注意,无处数学定义它的1/0 =的无穷的。其中的可能的跨$ P $磅这样的说法,但它是一个个人,快捷方式风格间pretation,而不是一个健全的事实。

Note that nowhere in mathematics it is defined that 1 / 0 = infinity. One might interpret it that way, but it is a personal, "shortcut" style interpretation, rather than a sound fact.

这篇关于除数为零:未定义行为或实施在C和/或C ++中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆