L20 [Unions, Function Pointers] - Skyline-9/CS2110-Notes GitHub Wiki
Union Introduction
union {
int myint;
char mychar;
char mystr[20];
} myun;
Looks like a struct
, behaves like a struct
, but what's the difference?
- All of the members have an offset of zero!
&myun.myint == &myun.mychar == &myun.mystr[0]
and sizeof(myun)
= size of the largest member
Union Example
Suppose we want to store information about athletes
For all, we want
- Name
- Jersey
- Team
- Sport
But for different sports, we want to track different data
- Ex: basketball we want shots, assists, rebounds, points, ... etc.
- Ex: football we want attempts, yards, TDs, Interceptions, etc.
struct player {
char name[20];
char jerseynum[4];
char team[20];
int player_type;
union sport {
struct football {...} footbstats;
struct baseball {...} basebstats;
struct basketball {...} baskbstats;
} thesport;
} theplayer;
Note that in this example, player is either a football player, either a baseball player, or either a basketball player. This way, we don't waste bytes in memory.
Applications of Unions
Unions are basically the C way of implementing polymorphism found in object-oriented languages
Unions may
- Be copied or assigned
- Have their address taken with &
- Have their members accessed
- Be passed as arguments to functions
- Be returned from functions
- Be initialized (but only the first member)
- C designed it so that unions are either the first member, the second member, or the third member, and they made the first one the default
Unions may not be compared!
Function Pointers
A function pointer is just the machine address for where your function is stored
int fi(void); //Function that returns an int
int *fpi(void); //Function that returns a pointer to an int
int (*pfi)(void); //Pointer to a function returning an int!
pfi = fi; // Legal assignment
pfi = fi(); //HAHAHAHA COMPILER ERROR
Example: custom comparison function pointer
int (* compar)(const void *, const void *));
What kind of value will you typically find in a pointer to a function?
- The address of the first word of the function code