Week 6: Functions - Part 2 BJ Furman 01OCT2012
The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers Program (global) scope File scope Function prototype Function scope Block scope How to make functions modify more than one value Function Example Function Practice
Learning Objectives Explain the structure of a function Explain the concept of identifier scope Explain the method by which functions can modify more than one value
Functions - Example Function prototype Remember semicolon!! Function definition Function call Function return optional for functions of type void or just, return ; can have multiple return statements can use anywhere in the function body Note: only one value can be returned #include /* function prototype */ double product(double x, double y); int main(){ double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
Functions - Definition Structure Function 'header' Return data type void if no value is returned Name Descriptive Arguments void if no data is passed into the function Statements Variable declaration Operations Return value (if any) Parentheses around the expression to return is optional type function_name (type arg1, type arg1, ) { statements; } double product(double x, double y) { double result; result = x * y; return result; }
Identifiers and Scope Identifier The name of a variable, function, label, etc. int my_var1;/* a variable */ pow_table();/* a function */ start:/* a label */ Question: Does it make a difference where in a program an identifier is declared? YES! --> concept of ‘scope’
Scope of Identifiers Scope of a declaration of an identifier The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope: Program (global scope) File Function prototype Function Block (“between the { } scope”)
Scope of Identifiers - Program Scope Program (global) scope if declared outside of all functions "Visible" to all functions from point of declaration Visible to functions in other source files Use only when necessary and then very carefully!! ex. from Ch var_scope.c #include int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
Scope of Identifiers - File Scope File scope Keyword static Makes variable a ‘visible’ only within this source file Use file scope to avoid naming conflict if multiple source files are used #include static int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
Function prototype scope Identifiers x and y are not visible outside the prototype Thus, names in the prototype do not have to match names in the function definition MUST match types, however! Scope of Identifiers - Function Prototype Scope #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) { double result; result = A * B; return result; }
Function scope Applies only to labels start: * * * goto start; Active from the beginning to the end of a function Ex. Statement labels in a switch selection structure Scope of Identifiers - Function Scope #include int main() { int user_sel; /* prompt user for entry */ /* get user entry */ switch( user_sel ) { case 1: printf("\n message..."); /* call game function1 here */ break; case 2: printf("\n message..."); /* call game function2 here */ break; default: printf("Error"); break; }
Scope of Identifiers - Block Scope Block (local) scope A block is a series of statements enclosed in braces { } The identifier scope is active from the point of declaration to the end of the block ( } ) Nested blocks can both declare the same variable name and not interfere ex. from Ch var_scope_block.c scope_nested_blocks.c #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
Storage Duration How long the identifier exists in memory Static storage class Identifier exists when program execution begins For variables: Storage allocated and variable is initialized once Retains their values throughout the execution of the program #include void just_count(void); /* proto */ int main() { int i; for(i=0;i<10;i++) { just_count(); } return 0; } void just_count(void) { static int count_a; int count_b; count_a = count_a + 1; count_b = count_b + 1; printf("count_a== %d\t", count_a); printf("count_b== %d\n", count_b); } just_count.c
For functions: function name exists when execution begins For variables with global scope: i.e., declared outside of all functions and uses static keyword "Visible" to all functions from point of declaration in this source file only Keeps data ‘private’ to this file only Storage Duration, cont. #include static int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
Scope of Identifiers - Practice 1 What kind of scope do the variables have? ii jj mm kk #include int i; static float m; int k=10; int main() { int j; for(j=0; j<5; ++j) { printf("j= %d", j); } { int k=7; printf("k= %d", k); }
Review of Scope Five types of scope: Program (global scope) File (just in the immediate source file) Function-prototype (just in the prototype) Function (applies only to labels) Block (“between the { } scope”) Static keyword identifiers start to exist at execution variables retain their value throughout variables with global scope are private to the file they are declared in
Memory Stores program instructions and data (variables, etc.) Address 0x10FE 0x10FF 0x1100 0xFFFF Memory (8-bit) Bit Each location has an ‘address’ Each location stores the information as ‘bits’ Binary ____its Zero or one 8 bits is one byte Information is ‘coded’ (ex. ASCII) Memory is ‘written’ or ‘read’ (Can represent using two hexadecimal digits)
ASCII Code
Extended ASCII Code
Variables and Memory Variables in general Variable declaration informs compiler of two things: 1. Name of the variable 2. Data type of the variable Actions caused: Bytes allocated in memory Symbol table with name, address, and value Can think of a variable as having two "values" Value of what is stored at the memory location (rvalue) Value of the memory location (its address) (lvalue) int var1 = 0; 10FE Var address 0 intvar1 Var valueVar typeVar name Symbol Table Memory (8-bit) Address x10FE 0x10FF Bit x1100 0x1101
Bit Memory (8-bit) Address x10FE 0x10FF Assigning and Using Variables Assigning a value to a variable ( i = 3; ) Value is copied to the address listed in the symbol table Using a variable in an expression ( j = i; ) Accesses the value of what is stored at the memory location is accessed short int i, j; i = 3; j = i; 1100 short intj 10FE Address short inti ValueTypeName Symbol Table Big-endian
Variables that store addresses We can define variables that store memory addresses Such a variable is called a “pointer”
Passing Arguments into Functions How are the arguments passed into functions? 'Pass by value' function arguments are expressions In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies The values of the expressions in the function call are not changed #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) { double result; result = A * B; return result; }
Functions Affecting Values Indirectly Instead of product() prod_sum() How can I get the function to give both product and sum? put * in front of variable name in prototype and function definition put & in front of variable names in function call #include void prod_sum(double x, double y, double *ptr1, double *ptr2); int main() { double var1 = 3.0, var2 = 5.0; double prod, sum; prod_sum(var1, var2, &prod, &sum); printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum); } /* function definition */ void prod_sum(double A, double B, double *rslt_prod, double *rslt_sum) { *rslt_prod = A * B; *rslt_sum = A + B; }
Review Functions pass copies of their arguments into the function To get multiple values returned Use pointers in the argument list of the prototype and function definition Use & in front of variable names associated with pointer arguments in function call
Returning Multiple Values - Practice 2 Write a function that returns the square and cube of a number Prompts user for the number Prints number, square, and cube Prompt, square- cube calculation, and print must all be functions Steps 1.Pseudocode for program logic The actions that your program will do Everyone individually 2 minutes 2.Form into groups of three Share pseudocode (3 minutes) Divide up task to build functions 3.Write code
References