Article View: comp.std.c
Article #2953Re: Casting const; Is this standard conforming?
From: John F. Woods
Date: Tue, 17 Nov 1992 17:53
Date: Tue, 17 Nov 1992 17:53
45 lines
2432 bytes
2432 bytes
rhl@grendel.Princeton.EDU (Robert Lupton the Good) writes:
>I've never used const modifiers, so I assumed that this would be OK,
>#include <stdio.h>
>int
>main()
>{
> const int i = 0;
> (int)i = 1; /* Fails */
This is a syntax error. "Lvalue casts" (a mistake so common they have a name)
have always been forbidden by the language (contrary to the opinion of some
compilers).
> *(int *)&i = 1; /* OK */
>
> return(0);
>}
>
>Thinking about ROMs my guess is that gcc and the IBM xlc compilers are
>correct to reject the former assignment, and that their acceptance of
>the latter is permitted, but could anyone comment?
The second is not a syntax error, nor does it violate a Constraint, so no
diagnostic is required. The behavior, however, is explictly undefined
according to the Semantics section of 3.5.3 Type Qualifiers: "If an attempt
is made to modify an object with a const-qualified type through the use of an
lvalue with non-const-qualified type, the behavior is undefined."
>What do you think about the portability of the cast?
If the hardware permitted it, the compiler would be perfectly at liberty to
use genuine read-only storage for that variable (perhaps it could allocate
a whole stack page for "i" and mark it as read-only in the MMU).
What you probably want is for the module that *defines* this variable to be in
a file by itself, with the declaration of the variable lacking the const
qualifier; every module that simply declares it with "extern" would include
the "const" qualifier. Unfortunately, that ALSO is illegal, since the types
"const <type>" and "<type>" are not compatible types, and all declarations
referring to the same object must have compatible type. However, this
particular transgression at least *sounds* sensible enough that you might be
able to sweet-talk your compiler vendor(s) into letting it work anyway.
C doesn't have a means to express what you want. You'll just have to
discipline yourself instead of asking the compiler to do it for you.
Technical Details
Message-ID:
<18867@ksr.com>Path:
arc1-ca.pugleaf.net!sparky!uunet!ogicse!emory!sol.ctr.columbia.edu!eff!world!ksr!jfwReferences:
<1992Nov16.200843.5565@Princeton.EDU>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!ogicse!emory!sol.ctr.columbia.edu!eff!world!ksr!jfw From: jfw@ksr.com (John F. Woods) Newsgroups: comp.std.c Subject: Re: Casting const; Is this standard conforming? Message-ID: <18867@ksr.com> Date: 17 Nov 92 17:53:43 GMT Article-I.D.: ksr.18867 References: <1992Nov16.200843.5565@Princeton.EDU> Sender: news@ksr.com Lines: 45