https://www.mycompiler.io/view/5k2L4pvl37j
https://replit.com/@mofelee/divide-by-zero#main.c
并且在 macos 中也是正常执行。。
1
huaweigg 2022-04-24 09:18:54 +08:00 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. |
2
knir 2022-04-24 09:20:32 +08:00 1
除以 0 是未定义行为,实现可以为所欲为
|
3
msg7086 2022-04-24 09:26:16 +08:00 1
因为他们的行为不要求一致。
|
4
mofe OP 哭了。。看起来应该自己写一个 substract 函数判断一下。
|
5
leimao 2022-04-24 09:40:43 +08:00 via iPhone
It is undefined by design.
|
6
lostpg 2022-04-24 09:44:58 +08:00 via Android
遇见 ub (
|
7
whenov 2022-04-24 09:55:05 +08:00
如果浮点数采用 IEEE 754 表示,那么非 0 除以 0 的结果是无穷大( INFINITY in math.h )
|
8
reallynyn 2022-04-24 10:50:57 +08:00 1
ub 是语言层面的,除 0 是异常中断,中断属于 os 层面的问题,只能说 os 对于中断的处理不一致
|
9
MegrezZhu 2022-04-24 11:11:05 +08:00 2
未定义行为包括但不限于:错误的结果、抛异常、进程退出、你家的猫过来打你一拳
|
10
mofe OP @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) 注册到处理器中 |
11
mofe OP 简单来说就是和 C 语言本身没关系,但凡 C 语言有什么奇怪的行为都是系统中定义的,C 语言只是一个老实的翻译器。
看起来学 C 语言不能光学语言,还得学习如何手搓操作系统。。。 |