14
Enums CSCI 112: Programming in C

enums - cs.montana.edufredric.vollmer/teaching/112/slides/enums.pdfCreating a named type from an enum •The _tat the end of custom type names is a standard practice •It lets us

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

EnumsCSCI112:ProgramminginC

FittingCdatatypestotherealworld• Sofar,we’veseenint,double,float andchar• Foralotofrealworlddata,thesefitwell!• Whatsortsofthingswouldbedifficulttorepresentwiththesetypes?

FittingCdatatypestotherealworld• Sofar,we’veseenint,double,float andchar• Foralotofrealworlddata,thesefitwell!• Whatsortsofthingswouldbedifficulttorepresentwiththesetypes?• Cardinaldirections• Leftorrighthandedness• Typesofbeer(IPA,Amber,etc.)• Daysofweek

Enumeratedtypes• Cgivesusenumeratedtypes(enums) torepresentitemsinacategory—forexampleNORTH,SOUTH,EASTandWEST• Enums letassociateanumericvalue withameaningfulalphanumericnameenum directions {NORTH, // 0SOUTH, // 1EAST, // 2WEST // 3

};

enum directions my_direction = WEST;

Why??• Wecouldeasilyjustsay,”We’llcallNorth0,South1,etc.”andstorethevalueasanint• Whyisanenum abetterchoice?

Howtheywork• Incode,enums letusrefertothingswithanidentifier (stringname)• ButtoC,thesedifferentitemsinanenum areactuallyoftypeint

• NORTH,SOUTH,EAST,WESTcorrespondto0,1,2,3

enum directions {NORTH,SOUTH,EAST,WEST

};

enum directions my_direction = WEST;int x = (my_direction== 3); // This expression is TRUE (x is 1)

Importanttoknow…• Youcanonlyuseanenum identifieronceperscope!• Forexample,youcan’thaveNORTHaspartoftwoenum definitions

• Youcannothaveanothervariablewiththesameidentifierasanenum identifier• Ex:Wecan’tdeclareint NORTH; sinceNORTHisanidentifierindirectionsenum

• Anenum wedeclarerepresentsanewtype• enum directions my_direction; saysthatthevariable“my_direction”isoftypetheenumeratedtype“directions”

Importanttoknow…still…• Wecanonlyassignvaluesofint typetoanenumeratedtypevariable.• Eitheranactualint type,oranidentifierfromtheenum• Ex:SOUTHand2areequivalent,andcanbothbeassignedtodirections

• Cdoesnocheckingtomakesurethevalueyouassignisspecifiedintheenum youdeclared• Wecanassign4356todirections, eventhoughithasnomeaningsinceonly0through3(NORTHthroughSOUTH)arespecified

Creatinganamedtypefromanenum• Insteadofhavingtorefertoourenumeratedtypeasenum <name>,wecandefineanewCdatatype!• Thetypedef reservedwordallowsustorenametypes

typedef enum {NORTH,SOUTH,EAST,WEST

} directions_t;

directions_t my_direction = WEST;

Creatinganamedtypefromanenum• The_t attheendofcustomtypenamesisastandardpractice• Itletsusimmediatelyseethatthisisatype,asopposedtoavariableorfunction• typedef canbeusedtoaliasanyCtype,notjustenums:

• Thissnippetallowsustouse“fred_t”insteadofint

typedef int fred_t;

fred_t x = 345;

Ok,whatcanwedowithenums?• Let’suseanenum torepresentdaysoftheweek.

• Becauseanenum isreallyanint underthehood,wecandoalotoffamiliaroperationswiththem

typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

} day_t;

Ok,whatcanwedowithenums?• Switchstatementday_t day_of_week = Tuesday;

switch( day_of_week ) {case Monday:// ugh, monday? really?break;

case Tuesday:// mehbreak;

...}

Ok,whatcanwedowithenums?• Arithmetic

• Theorderwedeclareourenum membersindoesmatterforarithmetic• Itshouldbe“inorder”forthetypeyou’restoring• Ex:NORTH,EAST,SOUTH,WEST(notSOUTH,WEST,NORTH,EAST)

direction_t direction = EAST;

direction_t toLeft = --direction; // Returns NORTHdirection_t toRight = ++direction; // Returns SOUTH

Exampleprogram• Let’swriteaprogramtodosomegymnasticswithdaysoftheweek