I recently decided to satisfy a long time curiosity of mine. What happens when you divide by zero in C? I had always simply avoided this situation with logic, but was curious how a language like C, which cannot throw a catchable exception, handles this situation.
Here was my very simple test (compiled with GCC on Windows 10):
int main()
{
double test1 = 1.0/0.0;
printf( "%f", test1 );
int test2 = 1/0;
printf( "%d", test2 );
}
The operation done with the double
types gave me a lovely little indication that the result was not a number: 1.#INF00
. All's fine so far..
However, when performing a divide by zero with int
types, the program, less than eloquently, "stopped working." I'm running this on Windows, so I was alerted with that lovely dialog.
I am curious about this behavior. Why is crashing the program the choosen solution for an integer division by zero? Is there really no other solution, say akin to the double
way, to handle division by zero? Is this the same behavior on every compiler, or just GCC?