0

Just having confusion what is the difference between the two structs. What does the order do to alter the definition? Thanks.

// 1 
struct list
{
    struct list* next;
    unsigned long val;
};

// 2
struct list
{
    unsigned long val;
    struct list* next;
}; 
  • 1
    Generically, changing the order of members can add or remove padding for the purposes of [memory alignment](https://stackoverflow.com/q/4306186/1707353) but if you adhere to accessing members in a standard way, then you shouldn't be too concerned about the order of members. – Jeff Holt Apr 09 '21 at 02:31
  • They are equivalent. Depending on the size of the elements on your platform there could be a difference in position or presence of padding but they are still equivalent. – Retired Ninja Apr 09 '21 at 02:31
  • **1** The second is neater in documenting when vertically drawing a list: last field `next` pointing to the next `struct list` below. **2** The first has a pointer field at the 0 offset of the struct. Some processor might have a more optimal instruction for that. **3** The only difference concerns padding of the fields. Pointer and long must be different length and there must be padding. Which is unlikely here. – Joop Eggen Apr 09 '21 at 02:33
  • I'd put the link _first_--it's easy to find. This might be more obvious with a more complex linked list element (e.g.) `struct list { struct list *next; unsigned long val; long arrcount; int *arrbase; int param[1000]; };` – Craig Estey Apr 09 '21 at 03:05

1 Answers1

1

Functionally, these two structs will work the same way. They might not be the same size though due to padding.

dbush
  • 205,898
  • 23
  • 218
  • 273