C/C++ Programming for Engineers: Functions Review

C/C++ Programming for Engineers: Functions Review

8/7/2018 C/C++ Programming for Engineers: Functions John T. Bell Department of Computer Science University of Illinois, Chicago Review Suppose a C++ array "data" was originally declared to have 10 elements as follows: int nElements = 10; double data[ nElements ]; How can the array size later be increased to 20 elements? A. By changing the variable nElements to 20. B. By redeclaring data as "double data[ 20 ];" C. By storing a number in the 20th position of data[ ]. D. Error. The above code is invalid to begin with, and won't compile. E. Impossible - There is nothing wrong with the code shown, but there is also no way to change the size of an array in C++ once it has been allocated space. 2 1 8/7/2018 Motivations for Writing Functions • Reuse code, without cutting and pasting. • Reduce errors. Test functions thoroughly, in all situations, then trust them to work right. • Incremental / Modular Development. Develop and test one piece at a time. • Improve readability, pulling code out of main. • Flexibility, through passed parameters. • Build libraries, e.g. sqrt( ), etc. 3 General Concept of Functions 1. When a function call is made, control transfers from the point of the call into the function. – If the function takes parameters, then information is passed from the calling code to the function. 2. The function executes, with associated effects. 3. When the function completes, it returns control back to the code that called it. – If the function returns a value, then that information is passed back to the calling code. 4 2 8/7/2018 General Syntax of a Function return_type function_name( arg_type argument, ... ) { local_variable_type local_variables; executable statement(s); return return_value; } 5 Simple Sample Function int add( int a, int b ) { int sum; sum = a + b; return sum; } 6 3 8/7/2018 Return Type • The “return type” indicates what kind of data this function returns, if any. Example: int. • Keyword “void” expressly states that this function does not return any value. ( Some languages would call this a “subroutine”. ) • If the return type is omitted, some compilers may assume some type. This is a bad idea. 7 Function Name • The function name is the name by which this function may be called. • Standard variable naming rules apply: – Begin with a letter. Continue with letters, numbers, or underscores only. – No two items ( in the same scope ) may have the same name. Don’t name functions and variables with the same names. 8 4 8/7/2018 Formal Parameter List ( arg_type argument, . ) • This lists the number of and types of data that are passed in to the function, and the variable names used within the function to received the passed information. • Each argument must have its type specified. • Keyword “void” indicates the function takes no input arguments. – Leaving the parentheses blank makes the compiler assume things. This is a bad idea. 9 Function Body • The main body of the function is contained within a pair of { curly braces }, which defines the function’s scope. • Any variables declared within the scope of a function, ( including the function arguments ), only exist within that scope, and cease to exist when the function returns. – There is no relationship between variables declared within one scope and variables with the same names declared in other scopes. ( More on scope later. ) 10 5 8/7/2018 Return statement • Execution of a return statement stops execution of a function, and returns control back to the code that called the function. • Only one return statement may be executed. • If the function returns a value, then exactly one item of the appropriate type follows the return keyword. E.g. “return 42;” or “return x;” • If the function is declared with a void return type, then no value is returned. E.g. “return;” 11 Preview Supposing a C++ function needs to send multiple values back to the function that called it. How can this be done? A. Using a single return statement with multiple values. B. Using multiple return statements. C. Using pass-by-reference parameters. D. Using an array of values, as long as all the values being sent back are all of the same data type. E. Either C or D would work. 12 6 8/7/2018 Calling Functions - Actual versus Formal Parameters • The variable names assigned to function parameters within the function are termed “formal” parameters. • The items passed by code when calling a function, whether variables or constants, are termed “actual” parameters. 13 Scope • “Scope” defines the range during which a variable exists and is accessible. • There are four types of scope to know: – Local variables – Function arguments ( a.k.a. formal parameters ) – GLOBAL variables – Very local variables 14 7 8/7/2018 The Scope of Local Variables • Local variables are declared inside of a function. • In C they had to be declared before any executable statements; In C++ they may be declared any time before they are used. • The scope extends from the point of declaration to the end of the function. • Local variables are not automatically initialized. 15 The Scope of Function Arguments • Function arguments (a.k.a. formal parameters), are exactly the same as other local function variables, except: • Formal parameters are initialized with values passed to the function when the function is called. • The scope of formal parameters is the entire duration of the function. 16 8 8/7/2018 The Scope of Global Variables • Global variables are declared outside of any function, usually at the beginning of a file. • The scope of a global variable is from the point of declaration to the end of the file. They are accessible by ALL functions within that range. • Global variables tend to cause lots of hard-to-find errors. They should never be used unless const or absolutely necessary. ( I.e. only consts in CS 109. ) • By convention, globals are in ALL CAPS (for humans. ) 17 The Scope of Very Local Variables • Very local variables are defined within a set of { curly braces }, such as within a loop, switch, or if-else construct. • Their scope extends from the point of declaration to the closing brace of their scope. • In this common implementation, “i” only exists within the for loop, and goes out of scope when the loop exits: for( int i = 0; i < nSteps; i++ ) { 18 9 8/7/2018 Eclipsing • When the same variable name is used in overlapping scopes, the variable with the more specific scope “eclipses” or hides the variable with the same name in the more general scope. A few examples: – A local variable will eclipse a global variable. – A very local variable will eclipse a local variable. – A local variable will eclipse a formal parameter*. • Note that the eclipsed variables continue to exist, and “reappear” when the eclipsing variable goes out of scope. * - If the compiler even allows this at all. 19 Function Declarations (Prototypes) versus Function Definitions • A function declaration informs the compiler of the existence of a function, its return type, and its parameter types, but does not define the function body. • A function definition defines the body of a function, possibly one that was previously declared but not yet defined. A function may be defined when declared. • Functions must be declared before they can be called, but they can be defined later. • The scope of function declarations parallels those of variables. They are normally declared globally at the beginning of files. ( e.g. #includes. See later slide. ) 20 10 8/7/2018 Function Prototypes • A function declaration made without its definition is known as a function prototype. • Prototypes improve readability, by allowing main( ) to appear before the functions it calls. • Parameter names are allowed in prototypes, and are good for humans, but are ignored by the compiler: – double delta( double max, double min, int nSteps); – double delta( double, double, int ); • Note that function prototypes end in a semicolon; 21 #include and Prototypes • “#include” says “Go find this other file and copy its contents into this place of the code.” • #included files often contain function prototypes, e.g. of math functions in <cmath>. • #included files in <angle brackets> are searched for in standard system directories. • #included files in “quotation marks” are searched for in the local directory, or sometimes in specified directories. 22 11 8/7/2018 Specifying Data Types in Parameters • Data types must be specified in function prototypes and definitions, but they are not included when calling the function. • Example prototype: ▪ double sqrt( double ); • Example function call: ▪ answer = sqrt( X ); // Note no “double” here. 23 Calling Functions - Parameters are passed by position, not by name. • The 1st actual parameter passed is used to initialize the 1st formal parameter in the function; the 2nd actual initializes 2nd formal, … • If the same variable name happens to be used in both calling code and called function, that is purely a coincidence. There is no relationship or connection between variables in different scopes based on their shared names. • Actual parameters can be reused. Formals not. 24 12 8/7/2018 Parameter Passing I - By Value • When an ordinary data type ( e.g. int, double ), is passed to a function, it is normally passed by value. • This means that only a number is sent from the calling code, which is used to initialize the formal parameter within the function. • Any changes made to the formal parameter remain local to the function, and have no impact on the calling code. ( What happens in functions stays in functions. ) • ( The variables passed by the calling code are termed the “actual” parameters. ) 25 Example of Pass By Value double func( double x, double z, double b, double c ); // prototype int main( void ) { double x( 1.0 ), y( 2.0 ), z( 3.0 ); z = func( x, y, z, x ); cout << « z = « << z << endl; 1.0 2.0 3.0 1.0 double func( double x, double z, double b, double c ) { return 0; } z += 2; // Affects local z only, not y or z in main return x + z * b / c; } 26 13 8/7/2018 Review How many asterisks would be printed by the following code? for( int i = 0; i < 42; i += 2 ) { int j = 0; do { cout << '*'; } while( ++j <= 0 ); cout << endl; } A.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    27 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us