patch to warn about direct compare of string literal

Tom Truscott trt@unx.sas.com
Wed Oct 20 10:19:00 GMT 1999


Here is a patch for gcc (for the file c-typeck.c).
It warns about programming mistakes such as:
    if (argv[i] == "-v") ...
This is a rare but potentially serious mistake.
I tried the patched gcc on a large collection of mature code
and it found about one mistake per million lines.
The only false positive so far has been on gcc itself:
enquire.c:1648: warning: suggest e.g. strcmp() when comparing string constant
		if ("abcd"=="abcd")
This particular warning could be suppressed with the following change:
		if ((char *)"abcd" == (char *)"abcd")

Tom Truscott

*** c-typeck.c.orig	Thu Sep 30 02:19:54 1999
--- c-typeck.c	Thu Oct  7 13:22:39 1999
***************
*** 1760,1765 ****
--- 1760,1771 ----
        && (TREE_CODE_CLASS (code1) == '<' || TREE_CODE_CLASS (code2) == '<'))
      warning ("comparisons like X<=Y<=Z do not have their mathematical meaning");
  
+   /* check for comparing string constant with anything besides simple zero */
+   if (TREE_CODE_CLASS (code) == '<' && extra_warnings
+       && (TREE_CODE (arg1) == STRING_CST || TREE_CODE (arg2) == STRING_CST)
+       && !integer_zerop (arg1) && !integer_zerop(arg2))
+     warning ("suggest e.g. strcmp() when comparing string constant");
+ 
    unsigned_conversion_warning (result, arg1);
    unsigned_conversion_warning (result, arg2);
    overflow_warning (result);


More information about the Gcc-patches mailing list