I'm getting into C and I experimented with union. My code is the following:
#include <stdio.h>
union date {
int year ;
char month;
char day ;
};
int main() {
union date birth;
birth.year = 1984;
birth.month = 7;
birth.day = 28;
printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
// return 1820,28,28
return 0;
}
1984 is written in binary as 0111 1100 0000
7 is written in binary as 0110
28 is written in binary as 0001 1100
I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.
I think you've misunderstood the purpose of a union. If you want an object that stores a set of properties (e.g. d.year, d.month, d.day), you need a struct.
Unions, in short, let you put one of a number of different types within a single variable. Say for example that you're implementing a filesystem. Let's say you want a variable current_block that can refer to either a super block or a data block, defined by struct super_block and struct data_block respectively. Then you could do:
union block_generic{
struct super_block;
struct data_block;
}
union block_generic current_block;
Now current_block can be either a super_block or a data_block.
EDIT: Just wanted to add a quick addendum about the actual usage of unions. Continuing the above example, to treat current_block as a super block, e.g., in order to access the filesystem's number of inodes, you would do current_block.super_block.n_inodes (what I mean to point out is that you don't give direct treatment to the union variable, you specify which "type hat," so to speak, it should wear.
Quoting C11, chapter §6.7.2.1, (emphasis mine)
The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa.
So, the basis of your expectation is wrong. You cannot have values for all the members of an union at the same time, you can have only one.
Also, from chapter §6.5.2.3, Footnote 95,
If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is re-interpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation.
Here, the last assigned value, day happens to be of the same size of that of month, so when you try to read day, it returns the value of that of the month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With