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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
An Introduction to Programming with C++ Fifth Edition
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
/* Documentations */ Pre process / Linking statements Global declarations; main( ) { Local Declarations; Program statements / Executable statements; }
Learners Support Publications Classes and Objects.
CPS120: Introduction to Computer Science Decision Making in Programs.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 6 Functions 6.1 Modular Design A valuable strategy when writing complex programs is to break down the program into several smaller modules. A module.
CSCI 171 Presentation 6 Functions and Variable Scope.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Lecture 12: Pointers B Burlingame 25 Nov Announcements Homework 6 due Homework 7 posted, due with the final  Final prep Take home Lab posted tonight.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Lecture 10: Peripherals Bryan Burlingame 04 November 2015.
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Lecture 15: Course Review BJ Furman ME 30 16MAY2011.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Lecture 7: Arrays BJ Furman 06OCT2012. The Plan for Today Announcements Review of variables and memory Arrays  What is an array?  How do you declare.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Lecture 7: Variable Scope B Burlingame March 16, 2016.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.
Functions + Overloading + Scope
Chapter 9: Value-Returning Functions
Chapter 7: User-Defined Functions II
C Functions -Continue…-.
Lecture 8: Variable Scope & Working with Files
Lecture 9: Pointers B Burlingame 25 October 2017.
User-Defined Functions
C++ for Engineers and Scientists Second Edition
6 Chapter Functions.
Classes and Objects.
Chapter 7: User-Defined Functions II
1-6 Midterm Review.
Submitted By : Veenu Saini Lecturer (IT)
C Language B. DHIVYA 17PCA140 II MCA.
Presentation transcript:

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? ii jj mm kk #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