c++gcc

C++ & GCC: How Does GCC's C++ Implementation Handle Division by Zero?


Just out of interest. How does GCC's C++ implementation handle it's standard number types being divided by zero? Also interested in hearing about how other compiler's work in relation to zero division. Feel free to go into detail. This is not purely for entertainment as it semi-relates to a uni assignment.


Solution

  • It doesn't. What usually happens is that the CPU will throw an internal exception of some sort when a divide instruction has a 0 for the operand, which will trigger an interrupt handler that reads the status of the various registers on a CPU and handles it, usually by converting it into signal that is sent back to the program and handled by any registered signal handlers. In the case of most unix like OSes, they get a SIGFPE.

    While the behavior can vary (for instance on some CPUs you can tell the CPU not to raise an exception, generally they just put some clamped value in like 0 or MAXINT), that variation is generally due to differences in the OS, CPUm and runtime environment, not the compiler.