Presentation is loading. Please wait.

Presentation is loading. Please wait.

Writing Functions.

Similar presentations


Presentation on theme: "Writing Functions."— Presentation transcript:

1 Writing Functions

2 The Big Idea What if this was how we did powers?

3 The Big Idea Functions provide Code Reuse Abstraction

4 Information Function header specifies everything but job of function
A contract to do work

5 Review A function declaration : Header
Body : Statements that do work of the function

6 A Function A function: -Called max -Takes two inputs (ints)
-Gives back an int

7 Using Max Using Max:

8 Full Program Must declare a function before it is used

9 Function Name Function name Normal identifier rules Use camelCase
no spaces, can't start with number, etc… Use camelCase Clearly identify job Readability > terseness Focus on verbs

10 Body Body of a function – where magic happens
Always a block of code { } Has own scope Variables declared inside only available inside

11 Parameters Parameters : information function needs
type name, type name, type name… OK to have no parameters int getHourOfDay()…

12 Parameters Parameters are special variables
Only exist within this function Initialized with value caller passes in: abs(10)  number = 10

13 Function type return pass answer back to caller
Must return right type of data

14 Function type return OK (but not great) to have more than one return
Every path must return

15 Void Functions Void : nothing Void function returns nothing
Just does some work Returns at }

16 Call Stacks Each function works in a separate stack frame in memory

17 Scope For Functions Scope of variable/parameter restricted to function it is declared in:

18 Scope For Functions Only variable available are: Parameters
New variables you declare in function

19 Global Something declared outside any function has global scope
Available anywhere in file (after declaration)

20 Global Uses Way to share information Class rules BAD : side effects
No variables at global scope Constants OK

21 Rules For Functions Communicate with params/return
Info to function : parameters Info from function : return value

22 Rules For Functions Do NOT use cin/cout

23 Rules For Functions Do NOT use cin/cout
Unless job of function is to print or get input

24 Comparison Return a grade: Print a grade:

25 Why Functions? Provide abstraction Provide reuse


Download ppt "Writing Functions."

Similar presentations


Ads by Google