简体   繁体   中英

Why integer division by zero doesn't crash the program compiled with gcc?

Integer division by zero is undefined and should result floating point exception and this is what happens why I write the following code

 int j = 0 ;
 int x = 1 / j;

In this case the program just crashes with FPE, but if I won't use variable and will go with literal values like this int x = 1 / 0; the the program doesn't crash, but just assigns some random value to x ! I tried to detect if int x = 1 / 0; really causes a crash by adding custom SIGFPE handler, but as I thought it is never invoked during literal zero division, but it does when I store 0 in a variable first. So, it seems that the literal zero division never actually crashes the program( I mean the division itself never happens), so does the compiler(GCC in my case) performs any tricks(eg substituting 0 with random number) in this case? or I misunderstood something?

Why integer division by zero doesn't crash the program compiled with gcc?

Well, I think the answer would be: because it can. It can crash. It can not crash.

or I misunderstood something?

From C11 6.5.5p5 (emphasis mine:p):

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 .

The behavior is not defined . It is not defined what should happen. It can "crash". It can not crash. It can spawn nasal demons . The program can do anything.

You should write only programs that you know how will they behave. If you want your program to "crash", call abort() .

so does the compiler(GCC in my case) performs any tricks(eg substituting 0 with random number) in this case?

The only way to know is to inspect the generated assembly code. You could use https://godbolt.org/

Since the expression contains division by zero constant, gcc could handle the issue at compile time.

If the division by variable valued 0, the compiler will give the responsibility to the exception handler because the evaluation is unpredictable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM