homer512 icon

init struct C99

homer512 | PRO | 09/21/16 03:22:41 PM UTC | 0 ⭐ | 543 👁️ | Never ⏰ | []
C |

1.18 KB

|

None

|

0 👍

/

0 👎

#include <assert.h>
/* using assert */
#include <string.h>
/* using memcmp */
 
struct Foo {
  int a, b;
};
 
struct Foo make_foo(void)
{
  struct Foo rtrn = {
    .a = 0,
    .b = 1
  };
  return rtrn;
}
 
void init_foo(struct Foo* foo)
{
  foo->a = 0;
  foo->b = 1;
}
 
struct Bar {
  struct Foo foo;
  int c;
};
 
struct Bar make_bar1(void)
{
  struct Bar rtrn = {
    .foo.a = 0,
    .foo.b = 1,
    .c = 2
  };
  return rtrn;
}
 
struct Bar make_bar2(void)
{
  struct Bar rtrn = {
    .foo = make_foo(),
    .c = 2
  };
  return rtrn;
}
 
void init_bar1(struct Bar* bar)
{
  bar->foo.a = 0;
  bar->foo.b = 1;
  bar->c = 2;
}
 
void init_bar2(struct Bar* bar)
{
  init_foo(&bar->foo);
  bar->c = 2;
}
 
int main(void)
{
  struct Bar bar0 = {
    .foo.a = 0,
    .foo.b = 1,
    .c = 2
  };
  struct Bar bar1 = make_bar1();
  struct Bar bar2 = make_bar2();
  struct Bar bar3, bar4;
  init_bar1(&bar3);
  init_bar2(&bar4);
  
  assert(! memcmp(&bar0, &bar1, sizeof(bar0)));
  assert(! memcmp(&bar0, &bar2, sizeof(bar0)));
  assert(! memcmp(&bar0, &bar3, sizeof(bar0)));
  assert(! memcmp(&bar0, &bar4, sizeof(bar0)));
  return 0;
}

Comments