Writing Functions
The Big Idea What if this was how we did powers?
The Big Idea Functions provide Code Reuse Abstraction
Information Function header specifies everything but job of function A contract to do work
Review A function declaration : Header Body : Statements that do work of the function
A Function A function: -Called max -Takes two inputs (ints) -Gives back an int
Using Max Using Max:
Full Program Must declare a function before it is used
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
Body Body of a function – where magic happens Always a block of code { } Has own scope Variables declared inside only available inside
Parameters Parameters : information function needs type name, type name, type name… OK to have no parameters int getHourOfDay()…
Parameters Parameters are special variables Only exist within this function Initialized with value caller passes in: abs(10) number = 10
Function type return pass answer back to caller Must return right type of data
Function type return OK (but not great) to have more than one return Every path must return
Void Functions Void : nothing Void function returns nothing Just does some work Returns at }
Call Stacks Each function works in a separate stack frame in memory
Scope For Functions Scope of variable/parameter restricted to function it is declared in:
Scope For Functions Only variable available are: Parameters New variables you declare in function
Global Something declared outside any function has global scope Available anywhere in file (after declaration)
Global Uses Way to share information Class rules BAD : side effects No variables at global scope Constants OK
Rules For Functions Communicate with params/return Info to function : parameters Info from function : return value
Rules For Functions Do NOT use cin/cout
Rules For Functions Do NOT use cin/cout Unless job of function is to print or get input
Comparison Return a grade: Print a grade:
Why Functions? Provide abstraction Provide reuse