gcc violates const-ness of variable?

Andrea Venturoli ml.diespammer at netfence.it
Thu Dec 2 01:52:19 PST 2004


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

Well, I do not know the precise answer, I'd have to look in the 
standards and have no time right now, so I'll just give you some pointers...

gcc -W -Wall code.c -> C compiler/you are compiling C code
g++ -W -Wall code.c -> C++ compiler/you are compiling C++ code

The source seems a mix of *standard* C and C++: stdio.h does not exist 
in C++, it might only be there for legacy code, but it works most of the 
times; IIRC "const" does not exist in *standardized* C...
gcc should ignore that (I guess), unless you specify -traditional.

"const" exists in C9X, which is not yet an official standard. I think 
gcc will support that, possibly with some command line switch or 
#define; I'm sure on Debian GNU/Linux some of the library features are 
turned on the latter way.


  bye
	av.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 2813 bytes
Desc: S/MIME Cryptographic Signature
Url : http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20041202/86b7a0b4/smime.bin


More information about the freebsd-questions mailing list