compiler detecting divide by zero

Geoffrey Rogers grogers at convex.com
Wed Nov 28 04:08:04 AEST 1990


In article <36233 at cup.portal.com> ts at cup.portal.com (Tim W Smith) writes:
>I tried the obvious:
>
>	int	i, j;
>
>	i = 1;
>	j = 0;
>	i/=j;
>

Most compilers today do constant folding and propogration on either
a local or global (with the entire function) optimization. This is
what you are getting bitting by.

>This one got past it:
>
>	j = 5;
>	for ( i = 0; i < 5; i++ )
>		j--;
>	i /= j;
>

The best way I found to get around this problem is by doing:

	div(0,1)
	...

	div(a,b)
		int a,b;
	{
		a = b/a;
	}

This will work for almost all compilers (expect compilers that can
do interprocedural optimizations, which there are not many). The
only time I have done something like this is for testing.

+------------------------------------+---------------------------------+
| Geoffrey C. Rogers   		     | "Whose brain did you get?"      |
| grogers at convex.com                 | "Abbie Normal!"                 |
| {sun,uunet,uiucdcs}!convex!grogers |                                 |
+------------------------------------+---------------------------------+



More information about the Comp.lang.c mailing list