------- Comment #9 from manu at gcc dot gnu dot org 2008-02-15 11:09 ------- (In reply to comment #0) > enum E { A }; > ... > E e = static_cast<E> (10); > > Yes, i know that result of this is undefined.
Is this true? I haven't found any mention of this. > However, previous versions of g++ (and every other c++ compiler i've used) > has implemented this in what seems like the simplest way: the compiler > simply assigns the value `10' to the enum value, regardless of the > fact that this is not a valid value for the enum. We assing 10 in GCC 4.3. > Therefore, the compiler is silently changing the behavior of the > code from what was likely intended. So i think a warning would > be appropriate in this situation. The current verison of 3.4 does > not issue any warning, even with `-Wall -pedantic'. The following patch implements the warning for this testcase. Do you know other cases that may be interesting to warn about? Index: gcc/testsuite/g++.dg/warn/pr12242.C =================================================================== --- gcc/testsuite/g++.dg/warn/pr12242.C (revision 0) +++ gcc/testsuite/g++.dg/warn/pr12242.C (revision 0) @@ -0,0 +1,4 @@ +// { dg-do compile } +// { dg-options "-Wall -Wextra -Wconversion" } +enum E { A }; +E e = static_cast<E> (10); // { dg-warning "warning.*undefined" } Index: gcc/cp/typeck.c =================================================================== --- gcc/cp/typeck.c (revision 132310) +++ gcc/cp/typeck.c (working copy) @@ -5069,10 +5069,15 @@ build_static_cast_1 (tree type, tree exp types which are integral, floating, or enumeration types can be performed. */ if ((INTEGRAL_TYPE_P (type) || SCALAR_FLOAT_TYPE_P (type)) && (INTEGRAL_TYPE_P (intype) || SCALAR_FLOAT_TYPE_P (intype))) { + if (TREE_CODE (expr) == INTEGER_CST + && TREE_CODE (type) == ENUMERAL_TYPE + && !int_fits_type_p (expr, type)) + warning (0, "this conversion is undefined"); + expr = ocp_convert (type, expr, CONV_C_CAST, LOOKUP_NORMAL); /* Ignore any integer overflow caused by the cast. */ expr = ignore_overflows (expr, orig); return expr; -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=12242