Chap11 - User-Defined Types
Chap11 - User-Defined Types
◼ arrays in a struct
2
Simple Type
⦿ A data type in which each value is atomic
(indivisible)
int x[2] =
{0,9};
0 9 ?
Array
x[0] x[1]
3
Primitive / Built-in type
4
C++ Primitive Type
integral short 2
int 4
long 4
float 4
floating double 8
void void -
5
User-defined Types
⦿ Allows programmers to create new data
types, tailored to meet the needs of a
particular program.
typedef
• to introduce a new name for an existing
type
⦿ Syntax:
7
typedef - Example
ED nn
8
typedef - Question
⦿ Modify the code below to use typedef Days as
integer type and define memory constants for
Monday (MON) to Sunday (SUN).
9
typedef - Answer
typedef int Days;
const int MON = 1;
const int TUE = 2;
const int WED = 3;
const int THU = 4;
const int FRI = 5;
const int SAT = 6;
cons int SUN = 7;
Days weekday[5] = {MON, TUE, WED, THU, FRI};
Days restday[2] = {SAT, SUN};
10
Enumeration type (enum)
⦿ A user-defined data type whose domain is an
ordered set of literal values (enumerators)
expressed as identifiers.
literal value, a.k.a. enumerator
must be unique in the scope
⦿ Example:
13
enum type - Variables
⦿ To define and initialize the variables of enum
type
EnumType VariableName;
⦿ Example:
15
enum type - Operation
⦿ Display the value of enum type variable will
obtain the index of enumerator
⦿ Example:
enum Weekdays {MON,TUE,WED,THU,FRI};
Weekdays workday = MON;
cout << workday;
index of MON = 0
The output is 0 is a number
16
enum type - Operation
⦿ Invalid enum type operation
enum Weekdays {MON,TUE,WED,THU,FRI};
Weekdays workday = MON;
workday = Weekdays(1);
this is valid
22
enum type (switch) - Question
⦿ Continuefrom the exercise in Slide 21, use
switch case to assign the respective price as
shown below to a variable named price.
Type Code Price (MYR)
Chicken Burger BGC 5.80
Beef Burger BGB 5.50
Fish Burger BGF 6.80
Burger
23
enum type - function
⦿ Return an enum type value from a function
enum Weekday {MON,TUE,WED,THU,FRI};
Weekday stringToDay(string);
int main()
{ string day = "Monday";
Weekday workday = stringToDay(day);
return 0;
}
Weekday stringToDay(string d)
{ if( d == "Monday")
return MON;
else if (d == "Tuesday")
return TUE;
...
}
24
enum type - Question
⦿ Fill in the blank:
enum Mood {SAD,HAPPY}; __③__ getMood(_④_ m)
__①____ {
int main() Mood emotion;
{ if(m==0)
int x = 1; emotion = SAD;
__②__ ans= getMood(1); else
return 0; emotion = HAPPY;
} return emotion;
}
25