Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions 2: Stupid Function Tricks

Similar presentations


Presentation on theme: "Functions 2: Stupid Function Tricks"— Presentation transcript:

1 Functions 2: Stupid Function Tricks

2 Type Coercion C++ will try to make values fit parameters

3 Type Coercion C++ will try to make values fit parameters

4 Overloaded Functions Overloaded Functions
same name different parameter list int max(int x, int y) double max(double x, double y) char max(char x, char y)

5 Overloaded Functions Overloaded Functions
same name different parameter list int foo(int x) int foo(double x) int foo(int x, int y) Which we used determined by call: foo(12); //must be using version 1 foo(4.5); //must be using version 2 foo(12, 13); //must be using version 3

6 Overloads Samples:

7 Overloads Compiler may be confused by multiple inexact matches

8 Not Overloading Need this call to be unambiguous:

9 Not Overloading Can not overload with different parameter names:

10 Not Overloading Same issue:

11 Not Overloading Can not overload with return type:

12 Default Arguments Provide default value for parameter with assignment in list: double round(double num, double places = 2) Used if actual parameter not provided: cout << round(PI, 2); cout << round(PI); //defaults to 2 places

13 Example:

14 Default Gotchas Parameters without defaults must go first No:
double round(double places = 2, double num)

15 Default Gotchas More than one parameter can be optional: void printDate(int year, int month = 0, double day = 0); Caller can't omit values from middle printDate(2012); //OK, month = 0, day = 0 printDate(2012, 10, 31.4); //OK printDate(2012, 10); //OK – month = 10, day = 0 printDate(2012, 31.4); //NO – bad

16 Shadowing Functions A variable with same name as function hides it:

17 Static Variables Statically initialized variables :
Local scope Only available in function Global duration Value persists between calls Declare with static keyword

18 Static Variables I can remember things! Good use of static
One time init Bad – everything else Side effects = bad

19 Inline Functions Don't bother

20 Recap Global Variables : NO Inline : NO
global const OK Inline : NO Static Variables : Probably Not Default Parameters : Probably Overloads : Yes


Download ppt "Functions 2: Stupid Function Tricks"

Similar presentations


Ads by Google