Why union doesn't work properly but struct does?

Debojit Acharjee 435 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

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,862 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,611 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,626 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,026 Reputation points
    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,711 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.