title: "Private" struct members in C with const
body: <p>In order to have a clean code, using some OO concept can be useful, even in C.
  I often write modules made of a pair of .h and .c files. The problem is that the user of the module have to be careful, since private members don't exist in C. The use of the pimpl idiom or abstract data types is ok, but it adds some code and/or files, and requires a heavier code. I hate using accessor when I don't need one.</p>
  <p>Here is a idea which provides a way to make the compiler complain about invalid access to &quot;private&quot; members, with only a few extra code. The idea is to define twice the same structure, but with some extra 'const' added for the user of the module.</p>
  <p>Of course, writing in &quot;private&quot; members is still possible with a cast. But the point is only to avoid mistakes from the user of the module, not to safely protect memory.</p>
  <pre><code>/*** 2DPoint.h module interface ***/
  #ifndef H_2D_POINT
  #define H_2D_POINT
  
  /* 2D_POINT_IMPL need to be defined in implementation files before #include */
  #ifdef 2D_POINT_IMPL
  #define _cst_
  #else
  #define _cst_ const
  #endif
  
  typedef struct 2DPoint
  {
      /* public members: read and write for user */
      int x;
      
      /* private members: read only for user */
      _cst_ int y;
  } 2DPoint;
  
  2DPoint *new_2dPoint(void);
  void delete_2dPoint(2DPoint **pt);
  void set_y(2DPoint *pt, int newVal);
  
  
  /*** 2dPoint.c module implementation ***/
  #define 2D_POINT_IMPL
  #include &quot;2dPoint.h&quot;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  2DPoint *new_2dPoint(void)
  {
      2DPoint *pt = malloc(sizeof(2DPoint));
      pt-&gt;x = 42;
      pt-&gt;y = 666;
  
      return pt;
  }
  
  void delete_2dPoint(2DPoint **pt)
  {
      free(*pt);
      *pt = NULL;
  }
  
  void set_y(2DPoint *pt, int newVal)
  {
      pt-&gt;y = newVal;
  }
  
  #endif /* H_2D_POINT */
  
  
  /*** main.c user's file ***/
  #include &quot;2dPoint.h&quot;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void)
  {
      2DPoint *pt = new_2dPoint();
  
      pt-&gt;x = 10;     /* ok */
      pt-&gt;y = 20;     /* Invalid access, y is &quot;private&quot; */    
      set_y(pt, 30);  /* accessor needed */
      printf(&quot;pt.x = %d, pt.y = %d\n&quot;, pt-&gt;x, pt-&gt;y);  /* no accessor needed for reading &quot;private&quot; members */
  
      delete_2dPoint(&amp;pt);
      
      return EXIT_SUCCESS;
  }
  </code></pre>
  <p>And now, here is the question: is this trick OK with the C standard?
  It works fine with GCC, and the compiler doesn't complain about anything, even with some strict flags, but how can I be sure that this is really OK?</p>