Presentation is loading. Please wait.

Presentation is loading. Please wait.

Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.

Similar presentations


Presentation on theme: "Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series."— Presentation transcript:

1 Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series

2 The GOAL for Week-3/4 Understand arrays Fully understand addressing Understand pointers (angel vs. devil) Understand references Master C/C++ control structures Fully understand the use of functions Fully understand call-by-value and call-by- reference Start modular design DEBUG_2: Basic skills: dump results Do the MP#2: A Command Line Interpreter

3 MP#2: Command Interpreter MP#2 description MP#2 demo So, to do that, what shall we learn? Make small “tools” or building blocks? Modular design? Put modules together? Find bug?

4 What to learn today? What motivates to use “function calls”? What is a function call? What is local variable? What is the return of a function call? What is exactly happening when invoking a function call?

5 Motivation … When you were doing your MP#1, you might have typed many times the following… if ( (buffer[st]>=‘a’ && buffer[st] =‘A’ && buffer[st]<=‘Z’) ){.. } Or char buffer[500], piece[100]; for(int i=st; i<=ed; i++) piece[i] = buffer[i+st]; piece[ed-st+1] = ‘\0’; This way, your code may look lengthy and messy  You may wonder: why should I type the same thing so many times? Is there a way to write it once, and use it whenever I want?

6 Motivation … Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program Boss/worker and blackbox –A boss asks a worker to perform a task and return (i.e., report back) the results when the task is done. –The boss does not care how the task is done, but only concerning about “inputs” and “outputs”. So, everything the worker has done is a blackbox to the boss –E.g., get the sqrt of a number! Can my program has such a mechanism?

7 Good News! Functions are invoked by a function call –Analogy: “Boss & worker” The boss --- the calling function or caller The worker --- the called function The boss does not need to care about how the worker gets the job done The boss just wants it done –A function call specifies the function name and provides information (as arguments) that the called function needs Function definitions –Only written once –These statements are hidden from other functions. function( ) input output

8 Think before coding! If I want to check if or not a char is a letter: –Input? –Output? If I want to copy a string to another char array: –Input? –Output? If I want to find a “segment” in a command line: –Input? –Output?

9 How to define a function? Create customized functions to –Take in data –Perform operations –Return the result Format for function definition: return-value-type function-name( parameter-list ) { declarations and statements; } Example : int square( int y) { return y * y; }

10 1. Function prototype 2. Loop 3.Function definition Program Output 1// Fig. 3.3: fig03_03.cpp 2// Creating and using a programmer-defined function 3#include 4 5using std::cout; 6using std::endl; 7 8int square( int ); // function prototype 9 10int main() 11{ 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; 14 15 cout << endl; 16 return 0; 17} 18 19// Function definition 20int square( int y ) 21{ 22 return y * y; 23} 1 4 9 16 25 36 49 64 81 100 Notice how parameters and return value are declared.

11 1. Function prototype (3 parameters) 2. Input values 2.1 Call function 1// Fig. 3.4: fig03_04.cpp 2// Finding the maximum of three integers 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8 9int maximum( int, int, int ); // function prototype 10 11int main() 12{ 13 int a, b, c; 14 15 cout << "Enter three integers: "; 16 cin >> a >> b >> c; 17 18 // a, b and c below are arguments to 19 // the maximum function call 20 cout << "Maximum is: " << maximum( a, b, c ) << endl;

12 3.Function definition Program Output 21 22 return 0; 23} 24 25// Function maximum definition 26// x, y and z below are parameters to 27// the maximum function definition 28int maximum( int x, int y, int z ) 29{ 30 int max = x; 31 32 if ( y > max ) 33 max = y; 34 35 if ( z > max ) 36 max = z; 37 38 return max; 39} Enter three integers: 22 85 17 Maximum is: 85 Enter three integers: 92 35 14 Maximum is: 92 Enter three integers: 45 19 98 Maximum is: 98

13 What can be in the inputs? The inputs of the function call is specified in the argument list (NOTE) the argument list can also be used to get the output through call-by-reference (you’ll learn that later) The argument list can have anything you want it there.

14 What can be a return? Unlike Matlab, C/C++ function only allows ONE return, which can be –A variable, e.g., int, double, bool… –A pointer, e.g., int*, double*, … –A reference, e.g., int&, double&, … –void, i.e., nothing

15 Function Prototypes Function prototype –Function name –Parameters Information the function takes in –Return type Type of information the function passes back to caller (default int ) void signifies the function returns nothing –Only needed if function definition comes after the function call in the program Example: int maximum( int, int, int ); –Takes in three int s –Returns an int

16 Math Library Functions Math library functions –Allow the programmer to perform common mathematical calculations.used > Example cout << sqrt( 900.0 ); –Calls the sqrt (square root) function. The preceding statement would print 30 –double sqrt(double x); Function arguments can be –Constant sqrt( 4 ); –Variable sqrt( x ); –Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );

17 Header Files Header files –Contain function prototypes for library functions –,, etc. –Load with #include Example: #include Custom header files –Defined by the programmer –Save as filename.h –Loaded into program using #include "filename.h"

18 Local Variables Local variables –Known only in the function in which they are defined –All variables declared in function definitions are local var. –The LIFE CYCLE of a local variable is only in the function in which it is used. Parameters –Local variables passed when the function is called that provide the function with outside information void main() { int x = 20; int y = myfunc(x); } int myfunc(t) { int x; x = t+1; return x; }

19 To have a deep understanding… Let’s understand the following: –Your program  machine code –Loading … –Instruction Pointer (IP) –Stack –Invoking a function call

20 Compiling and Linking Machine object code, e.g., a.obj Compiler Linker Various libraries Machine executable code (the stuff for machine to execute, not for you.  ) e.g., “a.exe” Your C/C++ source code (the stuff you wrote) e.g., a.cpp

21 Loading … Load.exe to memory (when you execute.exe) main( ) int func(a,b) func(a,b) x=func(3,4); 00601000 00602000 return c; Code seg.

22 Instruction Pointer How does the computer execute the program? main( ) int func(a,b) func(a,b) x=func(3,4); 00601000 00602000 return c; I. P. Code seg. Let me demonstrate this process in VC++ debugger! Question: when a function is called, for the I.P., (1)where to go? (2)how to get back from function call?

23 A Concept: Stack (LIFO) 20 34 12 20 push(20) 20 34 push(34) 20 34 12 push(12) 20 34 pop(12) 20 pop(34) pop(20)

24 Invoking a Function What happens when a function is invoked? –where is my code? –what happens to i.p.? –what happens to stack? –how to pass parameters? –how to get the return? 00601000 3 4 c main( ) int func(a,b) func(a,b) x=func(3,4); 00601000 00602000 return c; I. P. Code seg. stack

25 Question for Today! int fun(int x) { int y; y = x + 2; return y; } void main( ) { int y = 5; int x = 1; x = fun(x); } Question: after main() is executed, x=?, y=?

26 Prepare for MP#2 Take a look at my solution to MP#1, figure out which part can be replaced by function calls.

27 About MP#2 Attention, we only check 4 types of valid grammars. 1.assignment: "operand_1 = operand_2", e.g., a = 1 2.binary operation: "operand_1 operator operand_2", e.g., a + b 3.unary operation: "operand_1 operator", e.g., a++ 4.assignment and binary operation: "result = operand_1 operator operand_2", e.g., a = b + c According to that, we can define –Operations, (e.g., +, -, *, /, ++, --) –Operation types. (e.g., assignment, unary, binary) So, enum OP {ASN, ADD, MIN, MUL, DIV, INC, DEC}; enum OP_TYPE {asn, unary, binary};

28 A trick to do MP#2 You may want to find the # of segments of the command line –Since we only allow 2, 3, 5 Observe the position of operators (if defining a bool pIsOP[5] = {false, false, false, false, false}. –a + b{F, T, F, F, F} –c ++{F, T, F, F, F} –a = 1{F, T, F, F, F} –a = b + 1{F, T, F, T, F} From this observation, we only allow two patterns: –{F, T, F, F, F} and {F, T, F, T, F}


Download ppt "Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series."

Similar presentations


Ads by Google