From owner-freebsd-questions@FreeBSD.ORG Thu Dec 2 10:36:44 2004 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id DE98F16A4CE for ; Thu, 2 Dec 2004 10:36:44 +0000 (GMT) Received: from smtp1.adl2.internode.on.net (smtp1.adl2.internode.on.net [203.16.214.181]) by mx1.FreeBSD.org (Postfix) with ESMTP id 3B57F43D2F for ; Thu, 2 Dec 2004 10:36:44 +0000 (GMT) (envelope-from malcolm.kay@internode.on.net) Received: from beta.home (ppp35-69.lns1.adl1.internode.on.net [150.101.35.69]) iB2Aaf4Y097390; Thu, 2 Dec 2004 21:06:42 +1030 (CST) From: Malcolm Kay Organization: at home To: Rob , FreeBSD Date: Thu, 2 Dec 2004 21:06:41 +1030 User-Agent: KMail/1.5.4 References: <41AEC075.50207@yahoo.com> In-Reply-To: <41AEC075.50207@yahoo.com> MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200412022106.41384.malcolm.kay@internode.on.net> Subject: Re: gcc violates const-ness of variable? X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Thu, 02 Dec 2004 10:36:45 -0000 On Thu, 2 Dec 2004 05:42 pm, Rob wrote: > Hi, > > This should probably be discussed in the GNU gcc mailinglist. > But I'm more familiar here, and I first want to share it here > with other FreeBSD users. > > I'm surprised about this piece of code: > > #include > int main() > { > const int n = 0; > scanf("%d", &n); > printf("%d\n", n); > return 0; > } > It is of course wrong to pass a pointer to a 'const' object to scanf in either language. But the syntax is legal and does not require a diagnostic. > With gcc compiler, the constant variable 'n' will be overwritten > by the scanf statement. With g++ it (silently) is not. > So, I get following: > > $ gcc -W -Wall code.c > code.c: In function `main': > code.c:5: warning: writing into constant object (arg 2) > $ ./a.out > 9 > 9 > $ g++ -W -Wall code.c > code.c: In function `int main()': > code.c:5: warning: writing into constant object (arg 2) > $ ./a.out > 9 > 0 > But as for the difference bewtween C and C++ versions at run time this comes about from the differences in the languages. You must not assume C is some sort of subset of C++. The languages are distinctly different and one of the most important differences is in the meaning of the 'const' qualifier. So the same source has different meaning and should generate different code! > Is this a bug in gcc, or a feature? Neither, you are trying to equate two different languages. Malcolm