gcc violates const-ness of variable?

Rob spamrefuse at yahoo.com
Wed Dec 1 23:13:01 PST 2004


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;
  }

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

Is this a bug in gcc, or a feature?

Rob.




More information about the freebsd-questions mailing list