From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 10948 invoked by alias); 25 May 2007 14:36:30 -0000 Received: (qmail 10937 invoked by uid 22791); 25 May 2007 14:36:29 -0000 X-Spam-Check-By: sourceware.org Received: from smtp-out.google.com (HELO smtp-out.google.com) (216.239.45.13) by sourceware.org (qpsmtpd/0.31) with ESMTP; Fri, 25 May 2007 14:36:28 +0000 Received: from zps37.corp.google.com (zps37.corp.google.com [172.25.146.37]) by smtp-out.google.com with ESMTP id l4PEaLxX018724; Fri, 25 May 2007 07:36:21 -0700 Received: from smtp.corp.google.com (spacemonkey1.corp.google.com [192.168.120.115]) by zps37.corp.google.com with ESMTP id l4PEa6EI017289 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=NOT); Fri, 25 May 2007 07:36:06 -0700 Received: from localhost.localdomain.google.com (111.sub-70-212-208.myvzw.com [70.212.208.111]) (authenticated bits=0) by smtp.corp.google.com (8.13.8/8.13.8) with ESMTP id l4PEa2dY014071 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=NOT); Fri, 25 May 2007 07:36:04 -0700 To: Shriramana Sharma Cc: gcc-help@gcc.gnu.org Subject: Re: cast to an enum does not throw errors even for invalid values References: <46551213.40404@gmail.com> From: Ian Lance Taylor Date: Fri, 25 May 2007 14:38:00 -0000 In-Reply-To: <46551213.40404@gmail.com> Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-IsSubscribed: yes Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2007-05/txt/msg00257.txt.bz2 Shriramana Sharma writes: > Consider: > > enum BODY { SUN, MOON, STAR } ; > enum PLANET { EARTH, VENUS, MARS, PLUTO } ; > int main ( void ) > { > BODY body ; > // body = 1 ; // gives error. expected. > // body = EARTH ; // gives error. expected. > body = (BODY) 1 ; // no error. expected. > body = (BODY) EARTH ; // no error. expected. > body = static_cast < BODY > ( 1 ) ; // no error. expected. > body = static_cast < BODY > ( EARTH ) ; // no error. expected. > body = (BODY) 3 ; // no error. unexpected. > body = (BODY) PLUTO ; // no error. unexpected. > body = static_cast < BODY > ( 3 ) ; // no error. unexpected. > body = static_cast < BODY > ( PLUTO ) ; // no error. unexpected. > } > > I feel that the compiler should detect it when a value being casted to > an enum does not have an equivalent enum identifier. i.e. in the above > case, 3 and PLUTO (equivalent to 3 from the PLANET enum) do not have an > equivalent identifier in the BODY enum. But still the compiler does not > call an error. Even negative integers are "casted" to the target enum > without an error. These conversions are permitted by the C++ language. gcc could give a warning, but not an error, and certainly not a runtime error. Ian