Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 2 Dec 2004 21:06:41 +1030
From:      Malcolm Kay <malcolm.kay@internode.on.net>
To:        Rob <spamrefuse@yahoo.com>, FreeBSD <freebsd-questions@freebsd.org>
Subject:   Re: gcc violates const-ness of variable?
Message-ID:  <200412022106.41384.malcolm.kay@internode.on.net>
In-Reply-To: <41AEC075.50207@yahoo.com>
References:  <41AEC075.50207@yahoo.com>

next in thread | previous in thread | raw e-mail | index | archive | help
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<stdio.h>
>   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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200412022106.41384.malcolm.kay>