views:

332

answers:

4

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?

+14  A: 

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
NullUserException
Alternatively, turn off optimization :)
Lagerbaer
@Lager Of course :)
NullUserException
So, just to clarify, in my binary the line with the division just doesn't exist because the variable isn't used?
FireAphis
@FireAphis: yes. that's the point.
Donotalo
@FireAphis: if you were invoking a custom operator, and not a built-in one, chances are it would get executed nonetheless, because of possible side-effects.
Matthieu M.
A: 

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

Alexander Rafferty
That's a Microsoft-centric view - most environments do not translate machine exceptions such as divide by zero into C++ exceptions
Paul R
Nor VC++ does, IIRC on Windows divide by zero is by default a SEH exception.
Matteo Italia
It broke the program and gave me an unhandled exception when I compiled it.
Alexander Rafferty
@Alexander: do you mean a machine exception or a C++ exception ?
Paul R
@Matteo: from http://msdn.microsoft.com/en-us/library/6dekhbbc(VS.71).aspx : *"If the exception-declaration statement is an ellipsis (...), the catch clause handles any type of exception, including C exceptions and system- or application-generated exceptions such as memory protection, divide by zero, and floating-point violations."* This is the Microsoft-specific behaviour I was referring to.
Paul R
@Alexander: typically a divide by zero will invoke undefined behavior, on some architectures it may be trapped by the hardware, the C++ standard certainly doesn't guarantee anything afaik.
Matthieu M.
+10  A: 

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

volatile x = 1;
volatile y = 0;
volatile z = x / y;
GMan
i liked that ....
cateof
smart use of the language
John Dibling
@cateof @John Thanks. :)
GMan
+2  A: 

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.

Chubsdad