Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.

Similar presentations


Presentation on theme: "Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and."— Presentation transcript:

1 Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and debug the function once Avoid redundancy Procedural (top-down) approach design program, then fill in functions – “structured”

2 Sources of functions C++ (built-in)
Shared libraries (open source, for ex.) Other developers on a team Write it yourself

3 Elements of a Function Functions include: A name A return type
ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Functions include: A name A return type “Input” parameters, including a type and a name As needed, internal statements If “output” is desired, a return statement

4 Function name and type Functions are “called”, or invoked by name
ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Functions are “called”, or invoked by name The return type of the function determines the data type of the value that the function will “return” as its output Can be any valid C++ data type (ex: int, float, …) or even a user- defined data type (like a struct) Use the keyword void, if no output is required

5 Function Parameters ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } Function parameters (also called formal parameters) Serve as “inputs” to the function (by default) Listed in parenthesis after the function name separated by commas For each parameter, include a type and a name Can have as many parameters as desired Each with its own type

6 Function Statements ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } The number and type of internal statements in a function are determined completely by the task the function performs The writer of the function has the freedom to declare variables and write statements as needed Any variables declared are “local” to the function

7 Function – return statement
ftype fname (type1 par1, type2 par2, …) { variable declarations executable statements [return statement] } The return statement of a function serves as its “output” It can be a variable or an expression The resulting value will be cast to the type of the function declaration, if it doesn’t already match that type No return statement is needed if the function type is declared as “void”

8 Function Examples string getName() { string name;
float add(float x, float y) { float sum; sum= x + y; return sum; } void hello(string name) { cout << “Hello “ << name << endl; } string getName() { string name; cout << “Enter name: “; cin >> name; return name; }

9 Function Invocation Functions are called by Invoking the function name
Providing a list of “inputs” Items in the list are called arguments The arguments much match the defined function parameters by number and type But not, necessarily, by name z= add(a,b); // where a, b, and z are declared as floats After this statement is executed, z will contain the sum of a and b (using “add()” as declared previously)

10 Example $ ./a.out Enter a number: 2 The square of 2 is 4 $
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // compute the square, output it vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; $ ./a.out Enter a number: 2 The square of 2 is 4 $ vsqr gets assigned the return value of the function square

11 Local Variables and “Scope”
All variables in a function are “local” to the function Including both parameters (in the “input” list) And variables declared in internal function statements They are created “on-the-fly” when the function is invoked They are destroyed when the function returns (finishes) They have local scope Any modifications to a local variable do not affect variables in the calling routine even if they have the same name!

12 “Pass by Value” Any variable used in the function’s “input” list as an argument during a function call has it’s value copied, or “passed”, to the parameter variable The parameter value, with its copied value, can then used in the function as a local variable Any changes to the parameter variable do NOT affect the original argument variable from the calling routine They are separate variables, even if they have the same name! Because function variables have local scope!

13 Steps in Program Execution
Always begins in main() main() gets loaded on the “runtime stack” Statements on stack executed in order encountered When a function is encountered Code for the function is loaded on the runtime stack Values of the arguments are copied into the newly created parameter variables Code in runtime stack resumes execution (now in function code) Function code completes Return value copied to variable in main, if appropriate Function code removed from the stack, local variables and parameters are destroyed Runtime stack resumes execution of code in main() at the point after the function was called

14 Begin Execution main() num vsqr 2 ? Runtime Stack
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { return x*x; main() num vsqr 2 ? Runtime Stack main() gets loaded on the runtime stack User types “2”

15 Load Function Runtime Stack main() num vsqr 2 ? square() x sq
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 ? square() x sq square() gets loaded on the stack x and sq get created Value of num gets copied to x

16 Execute Function Runtime Stack main() num vsqr 2 ? square() x sq 4
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 ? square() x sq 4 Code in square() gets executed Result (4) is stored locally in sq

17 Return Value Runtime Stack main() num vsqr 2 4 square() x sq
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 4 square() x sq “replaced” by “4” Result (4) is copied back, i.e. returned, to vsqr in main() from sq in square() Imagine that square(num) is “replaced” by the “return value”

18 Destroy function Runtime Stack main() num vsqr 2 4
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; Runtime Stack main() num vsqr 2 4 square(), and its local variables are removed from stack main() completes execution

19 Prototypes A prototype is a function “declaration”
#include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; return 0; } // function definition float square(float x) { float sq= x*x; return sq; A prototype is a function “declaration” C++ is a “strongly typed” language All variables and functions must be declared before use A prototype tells the compiler that function exists and its form

20 Rules for Prototypes float add(float, float);
A prototype must contain The function name Its return type A list of parameter types Names of parameters are allowed but are not required float add(float, float); float add(float x, float y); Prototype must appear before first use of function Actual function definition can follow later Prototype not required if function definition occurs before use But common practice is to create prototypes

21 One more thing… Functions can be called using literals as arguments
It is not necessary to use a variable in a function call add(x,y); add(x,3); add(2,y); add(2,3); Are all valid function calls (Unless the formal parameter is a reference variable…)


Download ppt "Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and."

Similar presentations


Ads by Google