• Why use structs?

    To organize variables

  • How to use a struct?

    Syntax:

    Example:

  • Why use unions?

    To allow a variable to hold different types of values

  • How to use a union?

    Syntax:

    Example:

    union.c:

      Note:
    • program won't work if the union input was used at the end to display all the attributes at once
  • Struct vs Union

    A Truck AND A Robot vs A Transformer:

    Comparing A Struct and An Union
    ObjectProsCons
    A transformer is able to battle as a robot and transport as a truck
    only require one transformer to do both taskscannot do both tasks at once
    A robot to battle and a truck to transport
     
    can do both tasks at oncerequires a robot and a truck to do both tasks
    An union is able to use a memory block in multiple waysonly require one memory block to hold multiple types of datacannot store/use all types of data at the same time
    A struct is able to store multiple types of data at the same timecan store/use all types of data at the same timerequires more memory blocks to store/use all types of data

    Note: A lot of engineering is about trade-offs. There is rarely a perfect one-size fits all solution.