This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

[RFA] Close PR 150: division by zero


This simple patch + testcase closes PR 150, which is a request to warn
about compile-time division by zero, which can appear in non-obvious
ways from e.g. macros.

Bootstrapped x86 Linux, no regressions.  OK to commit?

Neil.

	* c-typeck.c (build_binary_op): Warn about division by zero.
	* testsuite/gcc.dg/divbyzero.c: New test.
	* testsuite/gcc.dg/noncompile/20010524-1.c: Update.

Index: c-typeck.c
===================================================================
RCS file: /cvs/gcc/gcc/gcc/c-typeck.c,v
retrieving revision 1.141
diff -u -p -r1.141 c-typeck.c
--- c-typeck.c	2001/10/11 03:15:23	1.141
+++ c-typeck.c	2001/10/21 20:21:54
@@ -1973,6 +1973,9 @@ build_binary_op (code, orig_op0, orig_op
     case FLOOR_DIV_EXPR:
     case ROUND_DIV_EXPR:
     case EXACT_DIV_EXPR:
+      if (integer_zerop (op1) || real_zerop (op1))
+	warning ("division by zero");
+
       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
 	   || code0 == COMPLEX_TYPE)
 	  && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
@@ -2026,6 +2029,9 @@ build_binary_op (code, orig_op0, orig_op
 
     case TRUNC_MOD_EXPR:
     case FLOOR_MOD_EXPR:
+      if (integer_zerop (op1))
+	warning ("division by zero");
+
       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
 	{
 	  /* Although it would be tempting to shorten always here, that loses
Index: testsuite/gcc.dg/divbyzero.c
===================================================================
RCS file: divbyzero.c
diff -N divbyzero.c
--- /dev/null	Tue May  5 13:32:27 1998
+++ divbyzero.c	Sun Oct 21 13:21:54 2001
@@ -0,0 +1,19 @@
+/* Copyright (C) 2001 Free Software Foundation, Inc.  */
+
+/* { dg-do compile } */
+
+/* Source: Neil Booth, Oct 21 2001.  PR 150 - warn about division by
+   zero.  */
+
+#define ZERO (4 - 6 + 2)
+#define DZERO (2.0 - 2.0)
+
+int main (int argc, char *argv[])
+{
+  int w = argc % ZERO;		/* { dg-warning "division by zero" } */
+  int x = argc / 0;		/* { dg-warning "division by zero" } */
+  int y = argc / ZERO;		/* { dg-warning "division by zero" } */
+  double z = argc / DZERO;	/* { dg-warning "division by zero" } */
+
+  return 0;
+}
Index: testsuite/gcc.dg/noncompile/20010524-1.c
===================================================================
RCS file: /cvs/gcc/gcc/gcc/testsuite/gcc.dg/noncompile/20010524-1.c,v
retrieving revision 1.2
diff -u -p -r1.2 20010524-1.c
--- 20010524-1.c	2001/05/25 06:34:16	1.2
+++ 20010524-1.c	2001/10/21 20:21:54
@@ -1,2 +1,2 @@
 int i = 7 / 0; /* { dg-error "not constant" } */
-
+	/* { dg-warning "division by zero" "div by zero" { target *-*-* } 1 } */


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]