Title: Tonight we will look at:
1Lecture 3
- Tonight we will look at
- typedefs
- enums
- structures
- unions
2Making Things More Humanly Readable
- As C/C developed, it was recognized, that it
might be a good idea to make it easier for
programmers to read their own and others
programs. - Had to find a way to do this without "breaking"
the language. - The first feature specifically added to do this
was the typedef. - Let's look at an example.
- (lect3_1.cpp lect3_2.cpp)
3Lect3_1.cpp
- Looking at lect3_1.cpp, the declaration
- int result1, result2
- is not very expressive.
- If we think about it, what are result1 and result
2? - Yes, they are of type int - but is there a more
expressive way to describe them? - result1 is a sum and result 2 is product.
- Let's look at lect3_2.cpp
4typedef
- Here we typedef'ed int variables to be a Sum and
a Product type. - Essentially, we gave the int type two aliases.
- We didn't change the fact that both Sum and
Product are ints, we just made the program more
readable. - Syntax for typedef
- typedef existingType newTypeAlias
- NOTE
- Our convention The newTypeAlias will begin with
a capital letter and all others will be lower
case. - Normally typedefs are placed in a header file and
included.
5enum
- enum is the second item added to C/C to make
things more readable and "natural". - It allows us to create our own types, which
contain a list of values that are members of this
new type (with an example, this will make
sense). - Syntax
- enum OurName enumerator, enumerator, ...
- Example
- enum WeekDay monday, tuesday, wednesday,
thursday, friday
6enum Facts
- Enumerators are not strings, but identifiers that
use the normal naming convention for specifying
identifiers (names of variables) - Internally, C/C converts the enumerators to
integers. - Ignore this fact - you could treat them as
integers within you program, but this is not good
programming practice. - enum GOTCHA If you print out the value of an
enum, it will not print the identifier (the
name), but the integer value that the compiler
assigned.
7What Can You Do With enums?
- Create variables of your enum type.
- Test operations.
- Iteration operations - (GOTCHA - can't use
autoincrement or decrement operators). - Assignment operations.
- Pass enum variable as a parameter.
- Let's look at some example code - lect3_3.cpp
8Structures
- In life, It is often convenient to gather
differing (by type) , but related information in
one place. - Example Address book
- Contains name, address, phone number for each
"entry" - In computer terms, this one entry that contains a
collection of types is called a record. - Each item in a record is called a field
- In C/C a record is called a struct and a field
is called a struct member - just what you needed,
more terms.
9struct
- If you recall, an array only allowed us to build
a collection of like types. - The struct is a built-in data structure that
allows us to mix types in one collection. - struct AddressBookEntry
-
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
10Defining a new struct "type"
- Here is the syntax for a struct
- struct StructSpecName
-
- memberList
-
- where each member of a member list is defined as
- dataType memberIdentifier
- struct AddressBookEntry // this acts like a new
type -
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
11Very Important Distinction
- struct AddressBookEntry // this acts like a new
type -
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
- This defines what an AddressBookEntry looks like,
it is not an "instance" of an entry. It is a
structure specfication, description, or template. - No memory is allocated as a result of this code
- Acts like a "template" for creating instances of
this type. (Think of it as a cookie cutter). - Actually creates a new "type".
12Creating an instance
- When we create an instance of a struct, only then
is memory allocated (use the cookie cutter to
create a cookie). Here is a code fragment to
illustrate this. - struct AddressBookEntry
-
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
- AddressBookEntry addressOfCynthia //
AddressBookEntry looks like a
//
"type" -
// addressOfCynthia is a variable -
// of type AddressBookEntry
13What does this like in memory?
- struct AddressBookEntry // this doesn't affect
memory utilization at run-time. -
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
- AddressBookEntry addressOfCynthia // but this
statement does
?
Name member
?
addressOfCynthis
Address member
?
Phone number member
14Initializing a struct with Declaration
- In the previous definition and declaration, we
created space for an addressBookEntry with the
name of addressOfCynthia. We did not initialize
the values within this struct and therefore they
contain unknown values. - To assign values within the declaration
statement, we use a syntax that looks somewhat
like the one we used for initializing an array
within a declaration statement.
15Initializing (continued)
- struct AddressBookEntry
-
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
- AddressBookEntry addressOfCynthia
-
- "Cynthia Suarez",
- "101 AnyStreet, AnyCity, NJ",
- 5555678
-
16Memory Picture with Initialized struct
- struct AddressBookEntry
-
- char name40 // name member
- char address60 // address member
- long phoneNum // phone number member
-
- AddressBookEntry addressOfCynthia
-
- "Cynthia Suarez",
- "101 AnyStreet, AnyCity, NJ",
- 5555678
-
Name member ( array of 40 char)
"Cynthia Suarez"
Address member (array of 60 char)
"101 AnyStreet, AnyCity, NJ"
AddressOfCynthis
5555678
Phone number member (long)
17Access to struct Members
- With simple types, like int, float, etc. we used
simple assignment of the name to access the
value. - With arrays, we used an index into the array to
access its members (called array elements). - To access the members of a struct we use a new
opertor called the "dot" operator or member
selector. - Syntax for member selection
- structIdentifierName.structMemberName
- both are "variable names"
18Accessing a struct Member (con't)
- What if Cynthia changes her phone number to
5551234, here is how we would change it in our
code
struct AddressBookEntry char name40 //
name member char address60 // address
member long phoneNum // phone number
member AddressBookEntry addressOfCynthia
addressOfCynthia.phoneNum 5551234 Let's
look at some code - lect3_4.cpp
19Nested structs
- A structure can contain any type including
another struct, array, or simple type.. - A nested struct is a struct contained with a
struct. - To access a member of a contained struct we use
"double dotted" notation. - Let's extend lect3_4.cpp to illustrate
(lect3_5.cpp) what we mean by "double dotted" - Syntax
- outterStructVariable.innerStructVariable.variable
- (ALL VARIABLE NAMES - NOT STRUCT TYPE NAMES)
20Functions and structs
- We can pass a structure to a function as a
parameter. - Implicitly this is done by "call by value"
- copy is made of structure on stack and "passed to
function" - Call by reference can be performed explicitly
- we will look at this when we cover pointers and
references - We can pass a structure back as a return value
from a function, since C supports structure
assignment as an aggregate operation.
21Syntax For Using structs with Functions
- Function prototype
- returnType funcName( struct StructSpecName)
- If returning a structure
- struct StructSpecNamee funcName(parameter list)
- When calling a function that requires a structure
parameter with call by value, use a structure
variable as the parameter. - Let's extend lect3_5.cpp to lect3_6.cpp to
illustrate this.
22Arrays of structs
- Array elements can hold any type as long as
elements of the array are of the same type. - Therefore, we can build an array of structures.
- Continuing with our example, we could add both
Jones and Smith to an array of Employee
structures, and then use iteration and indexing
to gain access to each employee's record.
23Syntax for an Array of structs
- Syntax
- struct StructSpecName arrayNameNUM_ELEMENTS
- Example
- struct Employee widgetCorpWorkers200
struct Employee
Index 0
struct Employee
Index 1
WidgetCorpWorkers
struct employee
Index 2
24Accessing Information From The Array of Structs
- The array will behave like any other array, with
the exception that it is holding a struct type
and not a simple type. - To gain access to the value of a struct variable
within the array, we need to combine the indexing
of the array to get to the correct structure
variable, and then use dotted notation to get to
the correct variable within the structure.
25Some Utilization Examples
- Declare an array of Employee structures
- struct Employee widgetCorpWorkers100
- To assign a specific Employee to one of the
widgetCorpWorker elements - widgetCorpWorkers0 jones // jones is
Employee - To gain access to jones' first name
- widgetCorpWorkers0.firstName
- widgetCorpWorkers0 resolves to a fully
qualified Employee structure - Jones - Let's look at example code, lect3_7.cpp
- Why are there 2 raises as part of the output?
26Unions
- Unions are rarely used, but we will mention them
here. - The declaration of a union looks like a struct,
but has the keyword union and acts totally
differently. - The union below sets aside memory for the largest
of the types contained within it. - A union, when invoked will contain only one of
its items not all of the items like a struct. - Depending upon the type of value that is assigned
to the union the union assumes that type. The
union will be either a 40 character string, a
float or a long. It always consumes the same
amount of memory no matter which type it
currently represents.
union someUnion char name40 // name
member float salary // address member
long phoneNum // phone number member
27Contrasting Arrays and Structures