gcc violates const-ness of variable?

Malcolm Kay malcolm.kay at internode.on.net
Thu Dec 2 02:36:45 PST 2004


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



More information about the freebsd-questions mailing list