Advertisement
homer512

init struct C99

Sep 21st, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include <assert.h>
  2. /* using assert */
  3. #include <string.h>
  4. /* using memcmp */
  5.  
  6. struct Foo {
  7.   int a, b;
  8. };
  9.  
  10. struct Foo make_foo(void)
  11. {
  12.   struct Foo rtrn = {
  13.     .a = 0,
  14.     .b = 1
  15.   };
  16.   return rtrn;
  17. }
  18.  
  19. void init_foo(struct Foo* foo)
  20. {
  21.   foo->a = 0;
  22.   foo->b = 1;
  23. }
  24.  
  25. struct Bar {
  26.   struct Foo foo;
  27.   int c;
  28. };
  29.  
  30. struct Bar make_bar1(void)
  31. {
  32.   struct Bar rtrn = {
  33.     .foo.a = 0,
  34.     .foo.b = 1,
  35.     .c = 2
  36.   };
  37.   return rtrn;
  38. }
  39.  
  40. struct Bar make_bar2(void)
  41. {
  42.   struct Bar rtrn = {
  43.     .foo = make_foo(),
  44.     .c = 2
  45.   };
  46.   return rtrn;
  47. }
  48.  
  49. void init_bar1(struct Bar* bar)
  50. {
  51.   bar->foo.a = 0;
  52.   bar->foo.b = 1;
  53.   bar->c = 2;
  54. }
  55.  
  56. void init_bar2(struct Bar* bar)
  57. {
  58.   init_foo(&bar->foo);
  59.   bar->c = 2;
  60. }
  61.  
  62. int main(void)
  63. {
  64.   struct Bar bar0 = {
  65.     .foo.a = 0,
  66.     .foo.b = 1,
  67.     .c = 2
  68.   };
  69.   struct Bar bar1 = make_bar1();
  70.   struct Bar bar2 = make_bar2();
  71.   struct Bar bar3, bar4;
  72.   init_bar1(&bar3);
  73.   init_bar2(&bar4);
  74.  
  75.   assert(! memcmp(&bar0, &bar1, sizeof(bar0)));
  76.   assert(! memcmp(&bar0, &bar2, sizeof(bar0)));
  77.   assert(! memcmp(&bar0, &bar3, sizeof(bar0)));
  78.   assert(! memcmp(&bar0, &bar4, sizeof(bar0)));
  79.   return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement