mofe
V2EX  ›  问与答

C 语言 x 除以 0 在各个平台的行为不一致,为什么?

  •  
  •   mofe · Apr 24, 2022 · 2784 views
    This topic created in 1659 days ago, the information mentioned may be changed or developed.

    抛出 SIGFPE

    https://www.mycompiler.io/view/5k2L4pvl37j

    正常执行

    https://replit.com/@mofelee/divide-by-zero#main.c

    并且在 macos 中也是正常执行。。

    11 replies  •  2022-08-04 17:30:21 +08:00
    huaweigg
    huaweigg
    Apr 24, 2022❤️1
    1
    > 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.

    > undefined behavior - there are no restrictions on the behavior of the program. Examples of undefined behavior are data races, memory accesses outside of array bounds, signed integer overflow, null pointer dereference, more than one modifications of the same scalar in an expression without any intermediate sequence point (until C++11)that is unsequenced (since C++11), access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.
    knir
    knir
    Apr 24, 2022❤️1
    2
    除以 0 是未定义行为,实现可以为所欲为
    msg7086
    msg7086
    Apr 24, 2022❤️1
    3
    因为他们的行为不要求一致。
    mofe
    mofe
    OP
    Apr 24, 2022
    4
    哭了。。看起来应该自己写一个 substract 函数判断一下。
    leimao
    leimao
    Apr 24, 2022 via iPhone
    5
    It is undefined by design.
    lostpg
    lostpg
    Apr 24, 2022 via Android
    6
    遇见 ub (
    whenov
    whenov
    Apr 24, 2022
    7
    如果浮点数采用 IEEE 754 表示,那么非 0 除以 0 的结果是无穷大( INFINITY in math.h )
    reallynyn
    reallynyn
    Apr 24, 2022❤️1
    8
    ub 是语言层面的,除 0 是异常中断,中断属于 os 层面的问题,只能说 os 对于中断的处理不一致
    MegrezZhu
    MegrezZhu
    Apr 24, 2022❤️2
    9
    未定义行为包括但不限于:错误的结果、抛异常、进程退出、你家的猫过来打你一拳
    mofe
    mofe
    OP
    Aug 4, 2022
    10
    @reallynyn 100 天后回复一下,interrupt 0 (除以 0 会触发的中断)是系统层面的行为,在 CPU 中定义好的

    出现这种 “除以 0” 的行为系统会跳到指定的内存位置找到指针,然后执行指定的中断代码。

    IA-32 和 x86-64 架构的 CPU 通过 [Interrupt Descriptor Table]( https://en.wikipedia.org/wiki/Interrupt_descriptor_table) 来定义相关行为

    然后通过 [LIDT]( https://docs.oracle.com/cd/E19455-01/806-3773/instructionset-82/index.html) 注册到处理器中
    mofe
    mofe
    OP
    Aug 4, 2022
    11
    简单来说就是和 C 语言本身没关系,但凡 C 语言有什么奇怪的行为都是系统中定义的,C 语言只是一个老实的翻译器。

    看起来学 C 语言不能光学语言,还得学习如何手搓操作系统。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1203 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 16:08 · PVG 00:08 · LAX 08:08 · JFK 11:08
    ♥ Do have faith in what you're doing.