tags:

views:

412

answers:

1

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.

Cheers, Chaz

+5  A: 

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.

Louis Gerbarg
Doesn't the SIGFPE get translated into a C++ exception throw? I realise that this isn't mandated by the C++ standard, but I'd have thought real-world compilers would at least have an option to do this. Not that I've ever given it much thought, in a lot of years of C++ use with several compilers.
Steve314
Steve: The SIGFPE is a runtime error which probably would be handled by an SE handler. Hint: _set_se_translator
MP24
And for Unix, it's the signal function to register a signal handler (which could throw convert to an exception): http://www.cplusplus.com/reference/clibrary/csignal/signal/
MP24
The thing is that it is not the C compiler that handles such things, it is a runtime error handled by the systemlibraries. Sometimes those libraries are included with the compiler, but often they are actually part of the OS. In any event, you control the behaviour with library calls, not compiler options.
Louis Gerbarg
C/C++ compiler…
Louis Gerbarg
@MP24 - thanks, that's a useful hint
Steve314