Records and Other Languages
Records - Other Languages
- Java: You know ...
- C and C++: Records are called structs
// Define a struct type (ie a record type)
struct Pair {int x; int y;}; // Declare type Pair (semi after }!)
struct Pair pair1, pair2, pair3; // Declare three Pairs
pair1.x = 1;
const int size = 3; // int const size = 3 also works
struct Pair a[size]; // Array of Pairs
// //////////////////////////////////////////////////////
// A Line is a nested record
// Typedef defines Line_t as a new name for this type
typedef struct Line {struct Pair p1; struct Pair p2;} Line_t;
Line_t l; // Declare a Line_t
A c example
and
prettified
C++:
- Can also use classes for composite types
- Structs and classes are very similar (ie almost identical)
- Fields are default public in structs, default private in classes
- Keyword struct not needed on variable declarations
- Structs can have functions and constructors, like classes
Could include some other languages ...
Variant Records in Other Languages
- C and C++ have Union - similar but less or no checking
- Unions do not have to be records - they simply allow sharing of memory
locations
- Example:
// Define a union type
union mytypes_t {
int i;
float f;
char c[4];
};
// Declare whatIsThis, a variable of union type
union mytypes_t whatIsThis;
// These all share the same memory location:
whatIsThis.i
whatIsThis.f
whatIsThis.c
Let's look at some real programs (programs under construction):
The Term Union
- A union type is the union of the types that make it up
- In a similar vein, a record is a cross product (ie a set of all tuples)