Why union doesn't work properly but struct does?

Debojit Acharjee 455 Reputation points
2023-05-29T13:30:51.0366667+00:00

In the following program the values of the variable "orange" is printed properly when "union" is changed to "struct", but why the int and float values don't print properly when "union" is used?

#include <stdio.h>

union fruit
{
  int number;
  float weight;
  char *color;
} orange;
  
int main()
{
  orange.number = 6;
  orange.weight = 1.3;
  orange.color = "orange";

  printf("There are %d %s colored oranges weighing %.2f pounds", orange.number, orange.color, orange.weight);

  return 0;
}

Output:

There are 4214884 orange colored oranges weighing 0.00 pounds

Developer technologies | C++
Developer technologies | Visual Studio | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 78,316 Reputation points Volunteer Moderator
    2023-05-29T15:02:29.1833333+00:00

    The union uses the same address for all the properties. This allows the same address to be interpreted as different types. A union will always be the value of the last assignment. In your case the literal.”orange”. When seen as a int, it’s the address, when seen as a float, it’s the address bits as a float.

    note. The sizeof of a union is the size of the largest property.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. David Lowndes 4,726 Reputation points
    2023-05-29T13:36:55.48+00:00

    You need to read up on what a union is.

    3 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.