C++ Functions and Structs

profilesandeep@45
07-csci515-StructsandEnums.pdf

Dr. Yuehua Wang [email protected]

Records (structs) and Enumeration

Records

◼ Recall that elements of arrays must all be of the same type

◼ In some situations, we wish to group elements of different

types

scores : 85 79 92 57 68 80 . . .

0 1 2 3 4 5 98 99

employee R. Jones 123 Elm 6/12/55 $14.75

Records (structs)

◼ struct: collection of a fixed number of components

(members), accessed by name

◼ Syntax:

C++ Programming: From Problem

Analysis to Program Design, Seventh

Edition

4

◼ C++ struct

◼ structured data type

◼ Fixed number of Components

◼ Components can be of different types, Called members (or fields)

◼ Accessed by name, not by index

◼ struct is a reserved word

◼ No memory is allocated for a struct

◼ Memory when variables are declared

◼ A struct is a definition, not a declaration

◼ Must declare a variable of that type to use it

struct employeeType

{

string firstName;

string lastName;

string address1;

string address2;

double salary;

string deptID;

};

struct studentType

{

string firstName;

string lastName;

char courseGrade;

int testScore;

int programmingScore;

double GPA;

};

//variable declaration

studentType newStudent;

studentType student;

//variable declaration

employeeType newEmployee;

employeeType employee;

◼ Note

◼ You can also declare struct variables when you define the struct.

For example, consider the following statements:

struct studentType

{

string firstName;

string lastName;

char courseGrade;

int testScore;

int programmingScore;

double GPA;

} tempStudent;

struct studentType

{

string firstName;

string lastName;

char courseGrade;

int testScore;

int programmingScore;

double GPA;

};

//variable declaration

studentType tempStudent;

◼ Typically, in a program,

◼ a struct is defined before the definitions of all of the functions in

the program

◼ so that the struct can be used throughout the program.

#include <iostream> using namespace std;

struct Employee {

short id; int age; double wage;

};

void printInformation(Employee employee) {

cout << "ID: " << employee.id << "\n"; cout << "Age: " << employee.age << "\n"; cout << "Wage: " << employee.wage << "\n";

}

int main() {

Employee joe = { 14, 32, 24.15 }; Employee frank = { 15, 28, 18.27 };

// Print Joe's information printInformation(joe);

cout << "\n";

// Print Frank's information printInformation(frank);

return 0; }

◼ Structures DO have aggregate operators

◼ assignment statement =

◼ parameter (value or reference)

◼ return a structure as a function type

◼ Limitations on aggregate operations

◼ no I/O

◼ no arithmetic operations

◼ no comparisons

cin>>newStudent; Cout<<newStudent

studentType temp; temp=newStudent+student;

if (student == newStudent) //illegal

Accessing struct Members

◼ Syntax to access a struct member:

◼ The dot (.) is called the member access operator

◼ To initialize the members of newStudent:

newStudent.GPA = 0.0; newStudent.firstName = "John"; newStudent.lastName = "Brown";

Assignment

◼ Value of one struct variable can be assigned to another

struct variable of the same type using an assignment

statement

◼ The statement:

◼ copies the contents of newStudent into student

student = newStudent;

◼ The assignment statement:

is equivalent to the following statements:

student.firstName = newStudent.firstName;

student.lastName = newStudent.lastName;

student.courseGrade = newStudent.courseGrade;

student.testScore = newStudent.testScore;

student.programmingScore = newStudent.programmingScore;

student.GPA = newStudent.GPA;

student = newStudent;

student = newStudent;

Comparison (Relational Operators)

◼ Compare struct variables member-wise

◼ No aggregate relational operations allowed

◼ To compare the values of student and newStudent,

◼ compare them member-wise,

if (student == newStudent) //illegal

if (student.firstName == newStudent.firstName && student.lastName == newStudent.lastName)

.

.

.

Input/Output

◼ No aggregate input/output operations on a struct variable

◼ Data in a struct variable must be read or written one member

at a time

◼ Example: read values from the keyboard and store them in members,

respectively

◼ Example: output newStudent contents

cin >> newStudent.firstName;

cin >> newStudent.testScore >> newStudent.programmingScore;

cout << newStudent.firstName << " " << newStudent.lastName

<< " " << newStudent.courseGrade

<< " " << newStudent.testScore

<< " " << newStudent.programmingScore

<< " " << newStudent.GPA << endl;

struct Variables and Functions

◼ A struct variable can be passed as a parameter by value

or by reference

◼ A function can return a value of type struct

void printStudent(studentType student)

{

cout << student.firstName << " " << student.lastName

<< " " << student.courseGrade

<< " " << student.testScore

<< " " << student.programmingScore

<< " " << student.GPA << endl;

}

void readIn(studentType& student)

{

int score;

cin >> student.firstName >> student.lastName;

cin >> student.testScore >> student.programmingScore;

cin >> student.GPA;

score = (newStudent.testScore + newStudent.programmingScore) / 2;

if (score >= 90)

student.courseGrade = 'A’;

else if (score >= 80)

student.courseGrade = 'B';

else if (score >= 70)

student.courseGrade = 'C';

else if (score >= 60)

student.courseGrade = 'D';

else

student.courseGrade = 'F’;

}

readIn(newStudent);

Arrays versus structs

Arrays in structs

◼ Two items are associated with a list:

◼ Values (elements)

◼ Length of the list

◼ Define a struct containing both items:

Arrays in structs (cont’d.)

Arrays in structs (cont’d.)

structs in Arrays

◼ Example:

structs in Arrays (cont’d.)

structs within a struct

Summary

◼ struct: collection of a fixed number of components

◼ Components can be of different types

◼ Called members

◼ Accessed by name

◼ struct is a reserved word

◼ No memory is allocated for a struct

◼ Memory when variables are declared

Enumeration

◼ typedef

◼ Create aliases to previously defined data types

◼ User defined data type

◼ Enumeration

Enumeration Type

◼ Data type: a set of values with a set of operations on them

◼ Enumeration type: is a user-defined type whose value is

restricted to one of several explicitly named constants

(enumerators)

◼ To define an enumeration type, you need:

◼ A name for the data type

◼ A set of values for the data type

◼ A set of operations on the values

Enumeration Type (cont’d.)

◼ You can specify the name and the values, but not the

operations

◼ Syntax:

◼ value1, value2, … are identifiers called enumerators

◼ List specifies the ordering:

value1 < value2 < value3 <...

◼ the default value assigned to value1 is 0, the default value

assigned to value2 is 1, and so on

Enumeration Type (cont’d.)

◼ The enumeration type is an ordered set of values

◼ Default value assigned to enumerators starts at 0

◼ A value used in one enumeration type

◼ cannot be used by another in same block

◼ Same rules apply to enumeration types

◼ declared outside of any blocks

◼ defines a new data type called colors

◼ the values belonging to this data type are BROWN, BLUE, RED,

GREEN, and YELLOW.

◼ defines standing to be an enumeration type.

◼ The values belonging to standing are FRESHMAN, SOPHOMORE,

JUNIOR, and SENIOR.

enum colors {BROWN, BLUE, RED, GREEN, YELLOW};

enum standing {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};

◼ Consider the following statements:

◼ Consider the following statements:

◼ If two or more enums contain constants with the same names,

this can lead to naming conflicts and compilation errors.

enum grades {'A', 'B', 'C', 'D', 'F’}; enum places {1ST, 2ND, 3RD, 4TH};

enum grades {A, B, C, D, F}; enum places {FIRST, SECOND, THIRD, FOURTH};

enum Status{CONTINUE, WON, LOST}; enum mathStudent {JOHN, BILL, CINDY, LISA, RON}; enum compStudent {SUSAN, CATHY, JOHN, WILLIAM};

Can and Can't

◼ You can specify the name and the values, but not the operations

◼ Can

◼ Declare Variables

◼ Assignment statements

◼ Relational Operators

◼ Functions

◼ Can't

◼ No arithmetic operations

Declaring Variables (Can do)

◼ Syntax:

Example:

◼ Can declare variables such as:

◼ Can also declare variables when defining the enumeration type

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};

sports popularSport, mySport;

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL} popularSport, mySport;

enum {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL} popularSport, mySport;

Assignment statement (Can do)

◼ Use the variable and set it’s value

◼ Values can be stored in enumeration data types:

◼ Stores FOOTBALL into popularSport

sports popularSport;

popularSport = FOOTBALL;

int num= 0;

bool flag= false;

◼ Consider the following statements:

int num= "A" ;

bool flag= 1.42;

sports popularSport;

popularSport = SUMMER;

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};

popularSport = FOOTBALL;

popularSport = BASEBALL;

popularSport = 1;

popularSport = 3;

Short summary

◼ Declaration

◼ Instantiation

◼ Operation

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};

Reserved word enum type

(list of constants separated by commas) Enumerators

0 1 5

sports popularSport, mySport;

popularSport = FOOTBALL; popularSport = BASEBALL;

Can and Can't

◼ You can specify the name and the values, but not the

operations

◼ Can

◼ Declare Variables

◼ Assignment statements

◼ Relational Operators

◼ Functions

◼ Can't

◼ No arithmetic operations

Relational Operators

◼ We can apply relational operatiors

if( num == 1 )

//do something

if( flag == false )

//do something

if (popularSport >= FOOTBALL)

//do something

◼ An enumeration type is an ordered set of values:

FOOTBALL <= SOCCER //is true

HOCKEY > BASKETBALL //is true

BASEBALL < FOOTBALL //is false

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL,

SOCCER, VOLLEYBALL};

◼ An enumeration type is similar to an integral data type

and can be used in loops:

◼ Question:

for (popularSport= BASKETBALL; popularSport <= SOCCER;

popularSport = static_cast<sports>(popularSport + 1))

popularSport = static_cast<sports>(popularSport + 1))

How to understand it

Input /Output of Enumeration Types

◼ Input and output are defined only for built-in data types such

as int, char, and double.

◼ An enumeration type cannot be input/output (directly)

◼ Have an integer/a string value and convert it to the enum type

◼ Output: by default, you'll get the integer value of the enum. If you want

to do something fancier than that, you'll have to handle it specially.

cin>>num;

cout<<num<<endl;

cin>>flag;

cout<<flag<<endl;

◼ Input

◼ or

int inputSport;

cin>>inputSport;

popularSport = static_cast<sports>(inputSport);

String inputStr;

cin>>inputStr;

if(inputStr == “BASKETBALL”)

popularSport = BASKETBALL;

if(inputStr == “FOOTBALL”)

popularSport = FOOTBALL;

sports to_enum(string &str)

{

if (str == "BASKETBALL")

return BASKETBALL;

else if (str == "FOOTBALL")

return FOOTBALL;

else if (str == "HOCKEY")

return HOCKEY;

//add more statements

return -1; // -1 in case the

parameter wasn't valid

}

String inputStr;

cin>>inputStr;

popularSport=to_enum(inputStr);

◼ Output

int inputSport;

cin>>inputSport;

popularSport = static_cast<sports>(inputSport);

cout<< popularSport<<endl;

◼ Alternative way

switch(popularSport){

case BESKETBALL:

cout<<"BESKETBALL"<<endl; break;

case FOOTBALL:

cout<<"FOOTBALL"<<endl; break;

case HOCKEY:

cout<<"HOCKEY"<<endl; break;

case BASEBALL:

cout<<"BASEBALL"<<endl; break;

case SOCCER:

cout<<"SOCCER"<<endl; break;

case VOLLEYBALL:

cout<<"VOLLEYBALL"<<endl; break;

default:

}

◼ Use a function Void printSports(sports& var){

switch(var){

case BESKETBALL:

cout<<"BESKETBALL"<<endl; break;

case FOOTBALL:

cout<<"FOOTBALL"<<endl; break;

case HOCKEY:

cout<<"HOCKEY"<<endl; break;

case BASEBALL:

cout<<"BASEBALL"<<endl; break;

case SOCCER:

cout<<"SOCCER"<<endl; break;

case VOLLEYBALL:

cout<<"VOLLEYBALL"<<endl; break;

default:

}

}

printSports(popularSport);

Functions and Enumeration Types

◼ Enumeration types can be passed as parameters to

functions either by value or by reference

◼ A function can return a value of the enumeration type

sports to_enum(string &str)

{

if (str == "BASKETBALL")

return BASKETBALL;

else if (str == "FOOTBALL")

return FOOTBALL;

else if (str == "HOCKEY")

return HOCKEY;

//add more statements

return -1; // -1 in case the

parameter wasn't valid

}

String inputStr;

cin>>inputStr;

popularSport=to_enum(inputStr);

◼ Use a function Void printSports(sports& var){

switch(var){

case BESKETBALL:

cout<<"BESKETBALL"<<endl; break;

case FOOTBALL:

cout<<"FOOTBALL"<<endl; break;

case HOCKEY:

cout<<"HOCKEY"<<endl; break;

case BASEBALL:

cout<<"BASEBALL"<<endl; break;

case SOCCER:

cout<<"SOCCER"<<endl; break;

case VOLLEYBALL:

cout<<"VOLLEYBALL"<<endl; break;

default:

}

}

printSports(popularSport);

Can and Can't

◼ You can specify the name and the values, but not the

operations

◼ Can

◼ Declare Variables

◼ Assignment statements

◼ Relational Operators

◼ Functions

◼ Can't

◼ No arithmetic operations

Can not do

◼ No arithmetic operations are allowed on enumeration

types

◼ ++ and -- are illegal, too:

◼ Solution: use a static cast

mySport = popularSport + 2; //illegal popularSport = FOOTBALL + SOCCER; //illegal popularSport = popularSport * 2; //illegal

popularSport++; //illegal popularSport– –; //illegal

popularSport = static_cast<sports>(popularSport + 1);

◼ After the second statement, the value of popularSport is HOCKEY.

◼Similarly, the statements:

◼ result in storing BASKETBALL in popularSport.

popularSport = FOOTBALL; popularSport = static_cast<sports>(popularSport + 1);

popularSport = FOOTBALL; popularSport = static_cast<sports>(popularSport - 1);

Problem 3

◼ Define an enumeration type Days, that has the values

◼ Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

◼ Write a problem that prompts the user to input a value

between 0 and 6 and outputs if it is weekend or not

◼ Example run 1:

◼ Example run 2:

Please enter the day of the week (0 to 6) 5

Emily still at work

Please enter the day of the week (0 to 6) 0

It is the weekend.

Exercises

◼ Q1: what is wrong with the following program?

◼ Q2: Consider the following C++ code:

◼ Q3: Consider the following function definition:

◼ Write the function prototypes of func

◼ Q4: Write the definition of a void function with three

reference parameters of type int, double, and string. The

function sets the values of the int and double variables to

0 and the value of the string variable to an empty string