home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / c / 19596 < prev    next >
Encoding:
Internet Message Format  |  1993-01-12  |  2.0 KB

  1. Path: sparky!uunet!paladin.american.edu!howland.reston.ans.net!spool.mu.edu!agate!dog.ee.lbl.gov!horse.ee.lbl.gov!torek
  2. From: torek@horse.ee.lbl.gov (Chris Torek)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: const and pointers in ANSI C
  5. Date: 12 Jan 1993 21:14:15 GMT
  6. Organization: Lawrence Berkeley Laboratory, Berkeley CA
  7. Lines: 51
  8. Message-ID: <28371@dog.ee.lbl.gov>
  9. References: <1993Jan12.164949.15684@clsi.COM>
  10. NNTP-Posting-Host: 128.3.112.15
  11.  
  12. In article <1993Jan12.164949.15684@clsi.COM> shankha@clsi.COM
  13. (Shankha Mitra) writes:
  14. >    typedef int *int_pointer;
  15. >    const int_pointer x;
  16. >    int_pointer const y;
  17.  
  18. [In ANSI C, x and y wind up with the same type, despite the fact that if
  19. the typedef is expanded as if it were a #define, they would wind up with
  20. different types.]
  21.  
  22. >My questions: 
  23. >1) Why this disparity in behavior between using explicit types (the first
  24. >   code fragment) and typedefed types (second code fragment)?
  25.  
  26. For the same reason that, e.g.,
  27.  
  28.     typedef int *iptr_t;
  29.     iptr_t a, b;
  30.  
  31. declares two pointers, rather than one pointer and one `int'.  Typedefs
  32. are not like #define's.  Although typedef'd names are not *new* types---
  33. they are simply alternative names for *existing* types---they must be
  34. treated as atomic entities.  Hence, `const' cannot `penetrate' a typedef.
  35.  
  36. Consider, e.g.,
  37.  
  38.     typedef double value_t;
  39.     const value_t x = X_INIT;
  40.     value_t const y = Y_INIT;
  41.  
  42. In this case, x and y are obviously both intended to be read-only.
  43. Suppose we later decide to change the representation of a value_t
  44. so that we can share values:
  45.  
  46.     typedef struct vblock {
  47.         int    refcount;
  48.         double    val;
  49.     } *value_t;
  50.  
  51. Because `const' does not penetrate typedefs, x and y remain `const'.
  52. If it did penetrate typedefs, suddenly x would be read/write, pointing
  53. to a read-only `struct vblock', while y would remain read-only and
  54. would point to a read/write `struct vblock'.
  55.  
  56. >2) Is it possible to make a declaration of a pointer to constant data
  57. >   using the typdefed int_pointer?
  58.  
  59. No.
  60. -- 
  61. In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 510 486 5427)
  62. Berkeley, CA        Domain:    torek@ee.lbl.gov
  63.