CSC195, Class 15: Structs and Other User-Defined Types Overview: * As little time as possible on structs, unions, and typedefs. * Lab * Reflection Notes: * Math research opportunities meeting after class. * Read about strings in K&R and man pages. * Questions about work this week? * Friday: Fun with strings ---------------------------------------- C lets you combine multiple variables into one big "structure" using the struct keyword struct { int x, int y } fred; You can now refer to fred.x and fred.y as variables More generally struct point { int x, int y }; defines the type named "struct point" with two fields, x and y. struct point wilma; You can now refer to wilma.x and wilma.y WHY BOTHER? * "To fail to accomodate object-oriented programming" * Easier to read, e.g., if you're doing 3D graphics programming for the guy with the tie + Group things together + Refer to the group by name rather than individually ---------------------------------------- C includes a fun variant called the union union whatever { int i, char ch }; HOW DO THEY DIFFER? * Structs assume you will use all their fields * Unions assume only one at a time * Good way to say "I need one of the following data types, but I'm not sure which one yet". * Advantage: You *can* share storage (but it's up to the implementer). ---------------------------------------- C lets you name other types with typedef TYPE NAME typedef int four_byte_integer WHY WOULD WE EVER BOTHER DOING THIS? * Makes the code clearer. * Permits some error checking. * The particular example I chose permits more portable code. ---------------------------------------- LAB * What's going on with typedef struct pair { int x; int y; } pair; "pair" is another name for "struct pair" One type, two names struct pair { int x; int y }; typedef struct { int x; int y; } pair; * Typedefs belong *outside* of your main(). * Why are wombats 8 bytes? * Don't forget your "friend" splint. * Nothing can precede declarations in a function body! * C vs. Java + Java class pair { int x; int y; } pair alpha = new pair(); pair beta = new pair(); alpha.x = 5; alpha.y = 6; beta = alpha; beta.x = 100; PRINT alpha.x; prints 100 Assignment is "beta refers to the same object as alpha" + C struct { int x; int y; } pair; pair alpha; pair beta; alpha.x = 5; alpha.y = 6; beta = alpha; beta.x = 100; PRINT beta.x Prints 5 Assignment is "copy fields of alpha into beta"