gpt4 book ai didi

c++ - 除以零 : Undefined Behavior or Implementation Defined in C and/or C++?

转载 作者:IT老高 更新时间:2023-10-28 13:03:05 26 4
gpt4 key购买 nike

关于除以零,标准说:

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 - 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):

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

标准是否有某种黄金法则,其中未定义的行为不能被(可能)矛盾的陈述所取代?除此之外,我认为如果您的实现定义了 INFINITY 宏,那么除以零被定义为这样的结论是不合理的。但是,如果您的实现没有定义这样的宏,则行为未定义。

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

注(1) C++03 标准谈到 <cmath>包含 INFINITY 宏的库。

最佳答案

我没有看到任何矛盾。除以零是未定义的,句号。没有提到 "... 除非 INFINITY 被定义" 在引用的文本中的任何地方。

请注意,在数学中没有任何地方定义 1/0 = 无穷大可能会这样解释,但这是一种个人的“捷径”风格解释,而不是一个可靠的事实。

关于c++ - 除以零 : Undefined Behavior or Implementation Defined in C and/or C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com