Why does the compiler not show an error when we try to divide a variable by zero

前端 未结 5 610
野的像风
野的像风 2021-01-06 08:20

If we try to run this code:

int d = 10/0;

We get a compiler error. So we cannot divide by zero.

Now consider this code:

<         


        
5条回答
  •  太阳男子
    2021-01-06 09:03

    In the first instance, you have two constants, and so the compiler resolves this at compile time, thus finding the error.

    In the second instance, as you have a non const variable(d), the compiler does not resolve this at compile time as it has no way of ensuring the value of d and thus will not spot the error. This will be evaluated at run time, where it will error out.

提交回复
热议问题