home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / std / c / 3018 < prev    next >
Encoding:
Internet Message Format  |  1992-11-17  |  2.3 KB

  1. Path: sparky!uunet!ogicse!emory!sol.ctr.columbia.edu!eff!world!ksr!jfw
  2. From: jfw@ksr.com (John F. Woods)
  3. Newsgroups: comp.std.c
  4. Subject: Re: Casting const; Is this standard conforming?
  5. Message-ID: <18867@ksr.com>
  6. Date: 17 Nov 92 17:53:43 GMT
  7. Article-I.D.: ksr.18867
  8. References: <1992Nov16.200843.5565@Princeton.EDU>
  9. Sender: news@ksr.com
  10. Lines: 45
  11.  
  12. rhl@grendel.Princeton.EDU (Robert Lupton the Good) writes:
  13. >I've never used const modifiers, so I assumed that this would be OK,
  14. >#include <stdio.h>
  15. >int
  16. >main()
  17. >{
  18. >   const int i = 0;
  19. >   (int)i = 1;                /* Fails */
  20.  
  21. This is a syntax error.  "Lvalue casts" (a mistake so common they have a name)
  22. have always been forbidden by the language (contrary to the opinion of some
  23. compilers).
  24.  
  25. >   *(int *)&i = 1;            /* OK */
  26. >        
  27. >   return(0);
  28. >}
  29. >           
  30. >Thinking about ROMs my guess is that gcc and the IBM xlc compilers are
  31. >correct to reject the former assignment, and that their acceptance of
  32. >the latter is permitted, but could anyone comment? 
  33.  
  34. The second is not a syntax error, nor does it violate a Constraint, so no
  35. diagnostic is required.  The behavior, however, is explictly undefined
  36. according to the Semantics section of 3.5.3 Type Qualifiers:  "If an attempt
  37. is made to modify an object with a const-qualified type through the use of an
  38. lvalue with non-const-qualified type, the behavior is undefined."
  39.  
  40. >What do you think about the portability of the cast?
  41.  
  42. If the hardware permitted it, the compiler would be perfectly at liberty to
  43. use genuine read-only storage for that variable (perhaps it could allocate
  44. a whole stack page for "i" and mark it as read-only in the MMU).
  45.  
  46. What you probably want is for the module that *defines* this variable to be in
  47. a file by itself, with the declaration of the variable lacking the const
  48. qualifier; every module that simply declares it with "extern" would include
  49. the "const" qualifier.  Unfortunately, that ALSO is illegal, since the types
  50. "const <type>" and "<type>" are not compatible types, and all declarations
  51. referring to the same object must have compatible type.  However, this
  52. particular transgression at least *sounds* sensible enough that you might be
  53. able to sweet-talk your compiler vendor(s) into letting it work anyway.
  54.  
  55. C doesn't have a means to express what you want.  You'll just have to
  56. discipline yourself instead of asking the compiler to do it for you.
  57.