Difference between structure and union

05 min read

Structure:

  • Memory needed to store a structure variable is the sum of the bytes required for every individual member in that structure.
  • All the members of a structure can be accessed simultaneously.
  • Altering the value of a member will not affect the other members of the structure.
  • Several members of a structure can be initialized at once.
  • Easier to work with.
  • Occupies more memory than a union.

Union:

  • Memory needed for a union variable is equal to the memory needed for storing the largest possible member in it.
  • Can access only one member at a time.
  • Altering the value of a member will affect the other members of the structure.
  • Only the first member of a union can be initialized. 
  • Should keep track of the currently active member of the union.
  • Comparatively, lesser memory is needed for a union variable than a structure variable of the same type
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error