66 lines
2.0 KiB
C
66 lines
2.0 KiB
C
#include <stdio.h>
|
|
// Bonus Question
|
|
|
|
struct s_Employee {
|
|
char name[50];
|
|
int id;
|
|
double hourly_salary;
|
|
int hours_worked;
|
|
};
|
|
union u_Employee {
|
|
char name[50];
|
|
int id;
|
|
double hourly_salary;
|
|
int hours_worked;
|
|
};
|
|
|
|
|
|
int main() {
|
|
// First to print the size of an int, double, and char[50] so we can see
|
|
printf("int is %d bytes\n", sizeof(int));
|
|
printf("double is %d bytes\n", sizeof(double));
|
|
printf("string of 50 length is %d bytes\n", sizeof(char[50]));
|
|
|
|
/* int is 4 bytes
|
|
* double is 8 bytes
|
|
* char[50] is 50 bytes
|
|
*
|
|
* Employee has 1 char[50], 2 ints, and 1 double
|
|
* All of these added up equal 66
|
|
* The largest of the all is char[50] at 50 bytes
|
|
*
|
|
*/
|
|
|
|
|
|
printf("Size of Struct employee: %d bytes\n", sizeof(struct s_Employee));
|
|
printf("Size of Union employee: %d bytes\n\n", sizeof(union u_Employee));
|
|
|
|
/* We see that the struct came out to 72 bytes, and the union came out to 66 bytes
|
|
* The struct's size is the sum of all its members, +6 bytes from the compiler for memory padding
|
|
* The unions size is just the size of its largest member, +6 bytes from the compiler for memory padding
|
|
*/
|
|
|
|
/* Thus, the struct should be able to assign and keep values for all its members
|
|
* The union can only hold one, as all members share memory
|
|
*/
|
|
|
|
// All the members of the struct will be assigned and are accessible together
|
|
struct s_Employee s_employee = {"John doe", 12345, 15.00, 8};
|
|
printf("Name: %s\n", s_employee.name);
|
|
printf("id: %d\n", s_employee.id);
|
|
printf("Salary: %0.02f\n", s_employee.hourly_salary);
|
|
printf("Hours worked: %d\n", s_employee.hours_worked);
|
|
|
|
// Only one member of the union can be assigned at a time
|
|
union u_Employee u_employee;
|
|
u_employee.id = 12345;
|
|
printf("id: %d\n\n", u_employee.id);
|
|
u_employee.hourly_salary = 15.00; // Now id is overwritten
|
|
printf("Salary: %0.02f\n", u_employee.hourly_salary);
|
|
printf("id: %d\n", u_employee.id); // Prints 0
|
|
|
|
|
|
|
|
return 0;
|
|
}
|