1 / 26

MSAS5104 Programming with Data Structures and Algorithms

Learn about functions in C++ programming, including the use of global and local variables, variable scope, and returning and passing values.

staleyr
Download Presentation

MSAS5104 Programming with Data Structures and Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MSAS5104Programming with Data Structures and Algorithms Week 7 Scott Marino Scott Marino MSMIS Kean University

  2. Functions Global Variables Local Variables Variable Scope Returning Values Passing Values By reference By value Topics Scott Marino MSMIS Kean University

  3. Functions • Functions are pieces of code written to perform specific tasks • The basis of creating objects is found in the use of functions • This is one of the enhancements of C++ over C • Every C++ program requires a “main” function, and can create as many of it’s own functions as it needs to Scott Marino MSMIS Kean University

  4. Functions • Functions need to be “declared” before the main function • Sometimes referred to as prototyping • #include <iostream>void info(void); // declare a function named infoint main (void); { main functions code… }void info(void) { // define the actual function … function info’s code …} Scott Marino MSMIS Kean University

  5. Functions • Values can be passed to functions and returned from functions • Using “void” tells the compiler that no value is passed to the function and/or returned from the function • Syntax: • void function-name(void); • The above function does not pass any values and does not receive any values Scott Marino MSMIS Kean University

  6. Functions • void calc_pay(void) { cout << “Hours worked?”; cin >> hours; cout << “Pay rate?”; cin >> payrate; gross = hours * payrate; cout << “Gross pay is “ << gross;} • The main function would execute the calc_pay function as calc_pay(); Scott Marino MSMIS Kean University

  7. Functions - Global Variables • The function example in the previous slide does not define it’s own variables • It expects the variables to be defined globally • Global variables are defined after the function prototypes and before the main function • Global variables are visible to the entire program and can be used inside any function Scott Marino MSMIS Kean University

  8. Functions - Global Variables • Global variables restrict the re-use of functions • Re-usable functions are typically self-contained • Global variables are created as program execution begins and exist for the entire time that the program is executing • In general, avoid using global variables except as constants Scott Marino MSMIS Kean University

  9. Functions - Local Variables • void calc_pay(void) { float hours, payrate, gross; // create local vars cout << “Hours worked?”; cin >> hours; cout << “Pay rate?”; cin >> payrate; gross = hours * payrate; cout << “Gross pay is” << gross;} Scott Marino MSMIS Kean University

  10. Functions - Local Variables • The function example in the previous slide defined it’s own variables • Those variables are referred to as “local” variables because they are defined within the function • Local variables are only visible within the function in which they are defined • They are created new each time the function is called and are destroyed when execution of that function is complete Scott Marino MSMIS Kean University

  11. Functions - Local Variables • The term “scope” is used to describe the areas in which variables are visible to a program • Variables with global scope are visible to the entire program • Variables with local scope are visible to specific functions within the program Scott Marino MSMIS Kean University

  12. Functions - Local Variables • C++ allows for a global and local variables to have the same name • Inside a function, the local variable takes precedence over a global variable with the same name • The scope of the variable is the area in the program in which the variable is valid (visible) Scott Marino MSMIS Kean University

  13. Variables - Scope • A block is the program code enclosed within curly braces { … } • Local variables can be named the same as a global variable and the local variable takes precedence inside the braces Scott Marino MSMIS Kean University

  14. Variables - Scope • Global variables are always permanent • They are created and initialized when the program starts, and remain until program termination • Local variables are temporary • Temporary variables are initialized each time the block of code is entered and are “destroyed” each time the block of code ends Scott Marino MSMIS Kean University

  15. Functions - Returning Values • float calc_pay(void) { float hours, payrate, gross; // create local vars cout << “Hours worked?”; cin >> hours; cout << “Pay rate?”; cin >> payrate; gross = hours * payrate; return gross;} Scott Marino MSMIS Kean University

  16. Functions - Returning Values • The function example in the previous slide will return the calculated value gross as the result of the function when called from the main function • int main(void) { float grosspay; … grosspay = calc_pay(); cout << “Gross pay is “ << grosspay; … } Scott Marino MSMIS Kean University

  17. Functions - Returning Values • In the main function, grosspay is assigned the returned value from the call to the calc_pay function • The calc_pay function prompts for the input values, calculates the gross pay, and returns the calculated value in the name of the function • Only a single value can be returned by a function • The data type of the variable receiving the returned result should match the data type of the value returned Scott Marino MSMIS Kean University

  18. Functions - Passing Values • float calc_pay(float hours, float payrate) { float gross; // create local vars gross = hours * payrate; return gross;} • Assumes that some other function or part of the program is responsible for inputting the hours and pay rate • This function only returns the value for gross pay Scott Marino MSMIS Kean University

  19. Functions - Passing Values • The function example in the previous slide will accept parameters for hours and payrate, and return a calculated gross pay amount • int main(void) { float grosspay, hours, payrate; …(code to prompt user for hours&payrate) … grosspay = calc_pay(hours, payrate); cout << “Gross pay is “ << grosspay; … } Scott Marino MSMIS Kean University

  20. Functions - Passing Values • In the main function, grosspay is assigned the returned value from the call to the calc_pay function • The main function is responsible for determining hours and payrate prior to calling the calc_pay function • Can create other functions to prompt for hours and payrate • Those functions can also validate the input data • Hours between 0 and 100 … Scott Marino MSMIS Kean University

  21. Functions - Passing Values • Data can be passed to a function via 2 methods, by value or by reference • Both methods have advantages and disadvantages and the use of each method needs to be carefully balanced • Faster vs. less control • Slower vs. more control Scott Marino MSMIS Kean University

  22. Functions - Passing Values • Passing data by value makes a local copy of the data each time the function is invoked • Making a copy involves allocating a block of memory and copying the data to it when the function is invoked • When the function completes, the memory is released back to the system • There are extra instructions required to allocate, copy, and free the memory • Generally safer since the original data cannot be modified Scott Marino MSMIS Kean University

  23. Functions - Passing Values • float calc_pay (float hours, float payrate) • The syntax of the passed values indicates to the compiler that the function should allocate 2 new variables, hours and payrate as type float • These are local copies of the data and are created at the start of execution of the function and are destroyed when the function ends Scott Marino MSMIS Kean University

  24. Functions - Passing Values • Passing data by reference is a method of passing a pointer to the original data instead of passing the data itself • By passing the address of the memory location instead of the actual data, there is no need to allocate, copy and free which results in faster execution • Generally less safe since the original data can be modified Scott Marino MSMIS Kean University

  25. Functions - Passing Values • float calc_pay (float &hours, float &payrate) • The & (ampersand) in front of the variable names instructs the compiler to pass the reference to the data and not the data itself • The variable name following the & can be different than the name passed, but should be kept the same (or similar) for readability • The function can update the passed data which can cause unexpected results Scott Marino MSMIS Kean University

  26. Functions - Passing Values • Passing by reference • Faster but less secure • Usually used for larger amounts of data like large arrays or long strings • Passing by value • Slower but safer • Usually used for smaller size data • Recommendation - for this classes homework and lab assignments, pass data by value Scott Marino MSMIS Kean University

More Related