Search code examples
c++divide-by-zero

How to cause an intentional division by zero?


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?


Solution

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

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