How to cause an intentional division by zero?

无人久伴 提交于 2019-12-08 15:31:51

问题


For testing reasons I would like to cause a division by zero in my C++ code. I wrote this code:

int x = 9;
cout << "int x=" << x;
int y = 10/(x-9);
y += 10;

I see "int =9" printed on the screen, but the application doesn't crash. Is it because of some compiler optimizations (I compile with gcc)? What could be the reason?


回答1:


Make the variables volatile. Reads and writes to volatile variables are considered observable:

volatile x = 1;
volatile y = 0;
volatile z = x / y;



回答2:


Because y is not being used, it's getting optimized away.
Try adding a cout << y at the end.

Alternatively, you can turn off optimization:

gcc -O0 file.cpp



回答3:


Division by zero is an undefined behavior. Not crashing is also pretty much a proper subset of the potentially infinite number of possible behaviors in the domain of undefined behavior.




回答4:


Typically, a divide by zero will throw an exception. If it is unhandled, it will break the program, but it will not crash.



来源:https://stackoverflow.com/questions/3863656/how-to-cause-an-intentional-division-by-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!