Functions in Programming
Functions in programming are pre-packaged blocks of code used to perform specific tasks, enhancing code reusability, reducing errors, and promoting a modular approach. They are essential for breaking down problems into manageable sub-tasks and improving code organization. Functions consist of a name, return type, input parameters, internal statements, and a return statement if output is required. They can be sourced from built-in C++ functions, shared libraries, other developers, or self-written code.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Functions A function is a pre-packaged block of code written to perform a well-defined task Sometimes referred to as Procedures, Methods, or Subroutines Functions are called by name Information (variables) is passed to the function Variables passed in are called arguments Execution of code statements in the calling routine is suspended Execution transfers to statements in the function Function uses the information passed in (if any) Function completes execution and returns any results to the calling routine Execution of code statements in the calling routine resumes from where it left off Professor John Carelli Kutztown University Computer Science Department
Functions Why? Code sharing and reusability Avoid redundancy Don t have to rewrite or duplicate code Reduces errors Debug the function once Procedural (top-down) approach Break problem into sub-tasks (compartmentalize) Write/test function for each sub-task Call the functions!!! Professor John Carelli Kutztown University Computer Science Department
Sources of functions C++ (built-in) Shared libraries (open source, for ex.) Other developers on a team Write it yourself Professor John Carelli Kutztown University Computer Science Department
Elements of a Function 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 Professor John Carelli Kutztown University Computer Science Department
Function name and type 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 Professor John Carelli Kutztown University Computer Science Department
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 Parameters accept information from arguments (which are passed in ) Professor John Carelli Kutztown University Computer Science Department
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 Professor John Carelli Kutztown University Computer Science Department
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 Professor John Carelli Kutztown University Computer Science Department
Function Examples 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; } Professor John Carelli Kutztown University Computer Science Department
Function Invocation Functions are called (or invoked) 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) Professor John Carelli Kutztown University Computer Science Department
#include <iostream> using namespace std; Example // prototype float square(float); int main() { float num; float vsqr; $ ./a.out Enter a number: 2 The square of 2 is 4 $ // 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; } vsqr gets assigned the return value of the function square // function definition float square(float x) { float sq= x*x; return sq; } Professor John Carelli Kutztown University Computer Science Department
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 have local scope they don t exist outside the function They are called automatic variables because They are created on-the-fly (automatically) when the function is invoked They are destroyed when the function returns (finishes) Any modifications to a local variable do not affect variables in the calling routine even if they have the same name! Professor John Carelli Kutztown University Computer Science Department
Pass by Value Any variable used in the function s input list as an argumentduring 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! Professor John Carelli Kutztown University Computer Science Department
Steps in Program Execution 1. Always begins in main() Information for main() gets loaded on the runtime stack 2. Statements are executed in order encountered 3. When a function is encountered a) Function information is loaded on the runtime stack (including parameter variables) b) Values of the arguments are copied into the newly created parameter variables 4. Execution transfers to the function code 5. Function code completes a) Return value is returned to the location where the function was originally called b) Function information is removed from the stack, local variables and parameters are destroyed 6. Execution of code in main() resumes a) at the point where the function was called, using the return value, as appropriate, in the calling expression Professor John Carelli Kutztown University Computer Science Department
#include <iostream> using namespace std; Begin Execution // 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; 2 ? num vsqr return 0; } main() // function definition float square(float x) { float sq; sq= x*x; return sq; } Runtime Stack main() gets loaded on the runtime stack User types 2 Professor John Carelli Kutztown University Computer Science Department
#include <iostream> using namespace std; Load Function // prototype float square(float); int main() { float num; float vsqr; 2 ? x sq // get input cout << "Enter a number: "; cin >> num; square() // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; 2 ? num vsqr main() return 0; } Runtime Stack // function definition float square(float x) { float sq; sq= x*x; return sq; } square() gets loaded on the stack o x and sq get created Value of num gets copied to x Professor John Carelli Kutztown University Computer Science Department
#include <iostream> using namespace std; Execute Function // prototype float square(float); int main() { float num; float vsqr; 2 4 x sq // get input cout << "Enter a number: "; cin >> num; square() // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; 2 ? num vsqr main() return 0; } Runtime Stack // function definition float square(float x) { float sq; sq= x*x; return sq; } Code in square() gets executed Result (4) is stored locally in sq Professor John Carelli Kutztown University Computer Science Department
Return Value #include <iostream> using namespace std; // prototype float square(float); 2 4 int main() { float num; float vsqr; replaced by 4 x sq square() // get input cout << "Enter a number: "; cin >> num; 2 4 // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; num vsqr main() return 0; } Runtime Stack 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 // function definition float square(float x) { float sq; sq= x*x; return sq; } Professor John Carelli Kutztown University Computer Science Department
Destroy function #include <iostream> using namespace std; // prototype float square(float); int main() { float num; float vsqr; // get input cout << "Enter a number: "; cin >> num; 2 4 // print output vsqr= square(num); cout << "The square of " << num << " is " << vsqr << endl; num vsqr main() return 0; } Runtime Stack // function definition float square(float x) { float sq; sq= x*x; return sq; } square(), and its local variables are removed from stack Output is printed main() completes execution Professor John Carelli Kutztown University Computer Science Department
#include <iostream> using namespace std; Prototypes // prototype float square(float); A prototype is a function declaration C++ is a strongly typed language All variables and functions must be declared before use 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; A prototype tells the compiler that function exists and provides its form the actual definition follows later return 0; } // function definition float square(float x) { float sq; sq= x*x; return sq; } Professor John Carelli Kutztown University Computer Science Department
Rules for Prototypes A prototype must contain The function name Its return type A list of parameter types Names of parameters are allowed but are not required They will be ignored 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 Professor John Carelli Kutztown University Computer Science Department
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 ) Professor John Carelli Kutztown University Computer Science Department