240 likes | 442 Views
Typedefs & Enums. Tricks for naming things. Typedef. typedef creates a new name for existing type Does not create new types! typedef exitingType newName ; Ex: typedef int number ; number x = 10; //number really means int. Why Typedef. Good uses Ugly constructs:
E N D
Typedefs & Enums Tricks for naming things
Typedef • typedefcreates a new name for existing type • Does not create new types! typedef exitingType newName; • Ex: typedefintnumber; number x = 10; //number really means int
Why Typedef • Good uses • Ugly constructs: std::vector<std:pair<int, int> >::iterator myIt; std::vector<std:pair<int, int> >::iterator myOtherIt; Vs: typedef std::vector<std:pair<int, int> >::iterator VectorPairIterator; VectorPairIterator myIt; VectorPairIterator myOtherIt;
Why Typedef • Good uses • Dealing with platform issues //On PC:typedefintint32;//On arduino processortypedeflong int32; //anywhere: int32 myNum; //int32 definitely has 32 bits
Constant Issue • Constants = readable code
Constant Issue • Don't protect us from stupidity:
Enums • Enumerated Type • Custom data type with discrete set of possible values A weekday is something from:{Monday, Tuesday, Wednesday, Thursday, Friday}
Enums • Syntax: enum newType {valueList}; • Sample enums: enum standing {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR}; enum color {RED, BLUE, GREEN, BLACK, ORANGE};
Enum Use • Enumusage • Can make variables of that type • Variables can only have given values enum standing{FRESHMAN, SOPHOMORE, JUNIOR, SENIOR}; standingstudentYear = FRESHMAN; standing student2Year = 12; //Error
Enums • Pluses of constants, without dangers
Enum Rules • Enum values must be valid identifiers • Start with letter, no special symbols, etc…
Enum Rules • Enum values must be valid identifiers • Can't reuse identifiers
Enum Values • Enums stored as integral values • Starting from 0: {Monday, Tuesday, Wednesday, Thursday, Friday} 0 1 2 3 4
Enum Values • Enums stored as integral values • Can modify by assigning {Monday, Tuesday, Wednesday, Thursday, Friday} 10 11 30 31 32
Enum Values • Only use assignment/value if represent logical value:
Relational Operators • Relational operations work based on assigned values (order of enumerated values)
Interacting: • Cin can't read into enum type • Read in string/int, use if:
Interacting: • Cout will print as number • Print using if/switch/array
Interacting: • Legal to switch based on enum:
Integral Values • Math with enum results in an int
Integral Values • Can static cast into an enum • Back to being dangerous
Integral Values • Can static cast into an enum • Back to being dangerous • Better:
Enum Passing • Work normally as parameteror return type: