Download presentation
Presentation is loading. Please wait.
Published byJesse Harper Modified over 8 years ago
1
enum
2
enum – a new type 2 enum is a set of constant int values, that defines a type: enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 };
3
enum – a new type 3 enum is a set of constant int values, that defines a type: typedef enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 } Season;
4
enum – a new type, usage 4 typedef enum Season {WINTER, SPRING, SUMMER, AUTUMN} Season; Season curr_seasons= SPRING; curr_season= 19; // legal, but UGLY! int prev_season= WINTER; // legal, but UGLY!
5
5 By default enums start with 0 and then +1 for each one. This can be changed: typedef enum Color { RED=2, GREEN, //==3 BLUE=8 } Color; enum – numbering
6
Use enum to eliminate magic numbers – alternative to #define 6
7
enums – why? readable More readable code less error prone Code less error prone debugger Accessible for debugger numerical values bad programming usually Use of the numerical values is not disabled, but bad programming usually! 7
8
8 switch
9
9 if (integer value == 3) //statement or block else if (integer value == 5) //statement or block switch (integer value) { case 3: //statement or block break; //optional. Otherwise fall-through! case 5: //statement or block case default: //statement or block }
10
switch & enum 10 typedef enum Season {WINTER, SPRING, SUMMER, AUTUMN} Season; Season s;... switch (s) { case WINTER: printf(“Cold and raining\n”); break; //optional. Otherwise fall-through! case SPRING: printf(“Nice weather\n”); break; //optional. Otherwise fall-through!
11
union
12
union – a new type A type that keeps (in different times) different types typedef union MyUnion { int i_val; double d_val; } MyUnion;
13
typedef union MyUnion { int i_val; double d_val; } MyUnion; MyUnion u; u.i_val= 3; printf("%d\n", u.i_val); u.d_val= 3.22; printf("%f\n", u.d_val);...... union – a new type, usage
14
14 goto
15
goto keyword goto bla; whee: //code here bla: //code there DANGER: SPAGHETTI CODE! Avoid whenever possible. Q: When do use? A: There are cases. e.g. : Break from a lot of nested loops Forward jump to error handler
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.