PATCH: avoid warnings on array[CHAR_CONSTANT]

Eddie Kohler kohler@icir.org
Tue Jun 10 01:21:00 GMT 2003


> Shouldn't this be based on the target's SCHAR_MAX, instead?  GCC supports
> platforms with 9-bit bytes.
> 
> Also, you'd need testcases, of course.

Yes, sorry -- and a ChangeLog entry. Here is an altered patch with both,
tested on i686-pc-linux-gnu.

Eddie


(gcc/cp)
	* typeck.c (build_array_ref): Don't warn about char-type array
	subscripts that are nonnegative integer constants no larger than
	SCHAR_MAX.

(gcc/testsuite/g++.dg/warn)
	* char-subscript.C: new test


Index: gcc/cp/typeck.c
===================================================================
RCS file: /cvsroot/gcc/gcc/gcc/cp/typeck.c,v
retrieving revision 1.463
diff -u -c -3 -p -r1.463 typeck.c
*** gcc/cp/typeck.c	19 May 2003 19:19:45 -0000	1.463
--- gcc/cp/typeck.c	10 Jun 2003 01:18:51 -0000
*************** build_array_ref (array, idx)
*** 2442,2450 ****
  	 So warn on any machine, but optionally.
  	 Don't warn for unsigned char since that type is safe.
  	 Don't warn for signed char because anyone who uses that
! 	 must have done so deliberately.  */
        if (warn_char_subscripts
! 	  && TYPE_MAIN_VARIANT (TREE_TYPE (idx)) == char_type_node)
  	warning ("array subscript has type `char'");
  
        /* Apply default promotions *after* noticing character types.  */
--- 2442,2455 ----
  	 So warn on any machine, but optionally.
  	 Don't warn for unsigned char since that type is safe.
  	 Don't warn for signed char because anyone who uses that
! 	 must have done so deliberately.
! 	 Don't warn for char constants whose values fit in the
! 	 positive range of 'signed char'. */
        if (warn_char_subscripts
! 	  && TYPE_MAIN_VARIANT (TREE_TYPE (idx)) == char_type_node
! 	  && (TREE_CODE (idx) != INTEGER_CST
! 	      || compare_tree_int (idx, 0) < 0
! 	      || compare_tree_int (idx, SCHAR_MAX) > 0))
  	warning ("array subscript has type `char'");
  
        /* Apply default promotions *after* noticing character types.  */


And the testcase (gcc/testsuite/g++.dg/warn/char-subscript.C):

// { dg-do compile }
// { dg-options "-Wall" }

// Copyright (C) 2003 Free Software Foundation, Inc.
// Contributed by Eddie Kohler 9 June 2003 <kohler@icir.org>

// warnings when char is used as a subscript

#include <limits.h>

int foo ()
{
    extern int a[256];

    int i = a[(char)-1];  // { dg-warning "array subscript has type `char'" }
    i += a[(signed char)-1];  // { dg-bogus "array subscript has type `char'" }
    i += a[(char)(SCHAR_MAX + 1)];  // { dg-warning "array subscript has type `char'" }
    i += a[(int)(SCHAR_MAX + 1)];  // { dg-bogus "array subscript has type `char'" }
    i += a[(char)SCHAR_MAX];  // { dg-bogus "array subscript has type `char'" }
    i += a['A'];  // { dg-bogus "array subscript has type `char'" }
    
    return i;
}



More information about the Gcc-patches mailing list