CSC209H1 Lecture Notes - Lecture 8: Function Pointer
Document Summary
Imagine that we are writing a simulation for a game about ducks in a lake. Each duck behaves differently, it has its own quack and y behaviour. Implementing different fly & quack behaviours void quack(){ puts( quack quack ); } void mute_quack(){ puts( <> ); } void fly_wings(){ puts( i am flying with my wings! ; } Ducks ducks[2]; ducks[0]. name = mallard ; ducks[0]. fly_type = fly_wings; ducks[0]. quack_type = quack; ducks[1]. name = domestic ; ducks[1]. fly_type = no_fly; ducks[1]. quack_type = quack; for(int i = 0; i < 2; i++){ simulate_duck(ducks[i]); Implementing simulate_duck void simulate_duck(duck *duck){ printf( i am a %s duck\n , duck->name); switch(duck->fly_type){ case fly_wings: fly_wings(); break; default: no_fly(); switch(duck->quack_type){ The rubber duck squeaks, the wooden duck cannot y, the space duck ies with. We would need to change the code for each. Need to introduce new types into each enum. Need to update switch statements with every new case.