Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed."— Presentation transcript:

1 ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

2 Syllabus Introduction Function Definition Parameter List Function Body Function Declaration Examples Recursion

3 2 Introduction A program can be divided into multiple parts Logical partitions are named: modules Physical partitions are named: C functions Each function has a name; when listed in a C program, the respective function is “called” or “invoked” to do its logical task at that code location Why are functions useful?  Organization – divides tasks into subtasks  Encapsulation – hides design and implementation details from view of the rest of the program  Simplification – reduces unnecessary code repetition  Modularity – creates reusable code libraries

4 3 Arguments, AKA actual parameters, contain data that the caller passes to the function  Arguments can be literal constants, variables, data structures, or expressions  Some functions require multiple arguments, while others may need no arguments at all The Return Value returns data back to the caller  A function can return a single value or no value at all, in which case it is a void function C Function Arguments Return Value

5 4 Example: Sample function calls: fun1();// no input arg, no ret val fun2( n );// 1 input arg, AKA 1 actual fun3( 1.25, "xm” );// 2 input args: 2 actuals R = rand();/* no arg, 1 return value */ y = sin( x );/* 1 arg, 1 return value */ w = pow( 2.5, 3 );/* 2 args, 1 return value */ /* 5 input args, 1 return value */ val = myfun( "PSU", 'x', 3.5, ivar, 2*cos( A ) );

6 5 Defining a Function return_type function_name ( parameter_list ) { // function_name local variable declarations code statements } //end function_name Function definition consists of:  header – defines required function inputs/outputs  body – defines the function code  Body includes return operation, even default fall-thru Function names follow variable naming rules Function body {between braces} Header

7 6 Parameter List: The formal parameter list defines expected data to be passed to function  Formal Parameters are local function variables, generally initialized at place of call via actuals  Names and data types of parameter are declared  Multiple parameters are separated by commas  During a call, the actual parameters are bound to the formal parameters  If no parameters are needed, the list is declared as type void

8 7 Are arguments (actuals) and parameters (formals) the same? → No. Arguments are the values passed to the function. Parameters are the function’s internal variables that hold copies of the passed values. Example: int x = 3, y = 5, k; char c = '#'; k = fun( x, y, 42, c );... int fun( int x, int y, int z, char c ) {... } The contents of variables x, y, c, along with the constant 42, are passed to the function. These are called arguments. These variables x, y, z, c receive the values passed to the function. They are called parameters.

9 8 Must an argument variable have the same name as its corresponding parameter variable? → No. They independent of one another Example: int a = 3, b = 5, k; char m = '#'; k = fun( a, b, 42, m );... int fun( int x, int y, int z, char c ) {... } Function callFunction definition '#' 42 53

10 9 Example: /* Function definition */ void display( int xval, char ch, double * ptr ) { // display printf( "%d %c %p\n", xval, ch, ptr ); } //end display int xval = 3, cat = 3; char ch = 'T', z = 'T'; double * ptr = & xval, * q = & xval; // careful!!! // Some function calls: display( 3, 'T', & xval ); // careful!!! display( xval, ch, ptr ); display( cat, z, q ); /* In each case, the value of the argument * is stored in the corresponding parameter */

11 10 If possible, an argument's type will be promoted or demoted to match its parameter's type Example: /* Function definition */ void fun( int u, double v ) {... } int x = 2; double y = 3.1415; /* Some function calls */ fun( x, y ); /* u contains 2, v contains 3.1415 */ fun( y, x ); /* u contains 3, v contains 2.0 */ Incompatible arguments can cause programs to fail at runtime! Be very carful!!

12 11 Return type: Return type can be:  Variant of char, int, float, double, struct  Pointer (i.e., memory address)  void (if no value is to be returned) If the function returns a value, then a return statement is needed in the function body. Example: double Compute_Vx (double V, double angle) { return V * sin( angle ); }

13 12 Function Body: Function body contains:  Local variable declarations  Local prototype declarations  Code that defines what the function does  Including code to specify return value Braces { } mark the beginning and end of the function body There is no semicolon after the final brace In C, a function definition cannot be nested inside another function definition! Note: gcc extension!

14 13 Example: /* Program #1 Compute areas of triangles - without separate function */ #include int main( void ) { // main float b, h; /* base and height */ float A1, A2; /* area */ A1 = ( 3.0 * 1.5 ) / 2.0; printf( "Area1 = %f\n", A1 ); b = 2.5; h = 15.4; A2 = ( b * h ) / 2.0; printf( "Area2 = %f\n", A2 ); b = 0.33; h = 5.7; printf( "Area3 = %f\n", ( b * h ) / 2.0 ); return 0; } //end main

15 14 Example: /* Program #2 Compute areas of triangles – with function */ #include float triangle_area( float base, float height ) { // triangle_area return ( base * height ) / 2.0f; } //end triangle_area int main( void ) { // main float b, h; /* base and height */ float A1, A2; /* area */ A1 = triangle_area( 3.0f, 1.5f ); printf( "Area1 = %f\n", A1); b = 2.5f; h = 15.4f; A2 = triangle_area( b, h ); printf( "Area2 = %f\n", A2); b = 0.33f; h = 5.7f; printf( "Area3 = %f\n", triangle_area( b, h ) ); return 0; } //end main

16 15 Declaring a Function Functions must be defined before they are first used Does this imply that functions must be placed in the source file in a specific order?  It depends For functions, C has two approaches to meet the "define-before-use" rule:  Define functions in order within the source file  Use function prototypes

17 16 Approach #1: Ordered Definitions Within the source file, function definitions that are used first are placed before functions that call them Example: Suppose A, B, C, D are functions. B calls C, D calls C, and A calls D: CBDACBDA Top of source file

18 17 Example: void fun1( void ) { // fun1 int x;... x = 3; } //end fun1 void fun2( void ) { // fun2 int x;... x = 5; fun1(); } //end fun2 int main( void ) { // main int x; x = 7; fun1(); fun2(); return 0; } //end main fun1 defined 1 st since both fun2 and main call it. fun2 defined 2 nd since main calls it (but not fun1 ). main defined last

19 18 Approach #2: Prototypes A function can be declared before being defined A function declaration is just the function header by itself followed by a semicolon (no body) These declarations are called prototypes Prototypes are usually placed at the top of the source file before the actual function definitions Prototypes allow the compiler to determine the basic input/output characteristics of functions without needing to know the internal details By the end of the compilations, bodies for the prototypes must be available

20 19 Example 1, with formal parameter names: #include /* Function prototypes */ void display( char ch, int xval ); float calculate( int x ); int main( void ) { // main display( 'G', 8 ); return 0; } //end main /* Function definitions */ void display( char ch, int xval ) { // display printf( "%c %d %f\n", ch, xval, calculate( xval ) ); } //end display float calculate( int x ) { // calculate return x*x / 3.0; } //end calculate Once the prototypes are declared, the order in which the functions are defined does not matter NOTE: The main() function does not need to be declared.

21 20 Example 2 without formal parameter names: #include /* Function prototypes */ void display( char, int ); float calculate( int ); int main( void ) { // main display( 'G', 8 ); return 0; } //end main /* Function definitions */ void display( char ch, int xval ) { // display printf( "%c %d %f\n", ch, xval, calculate( xval ) ); } //end display float calculate( int x ) { // calculate return x*x / 3.0; } //end calculate

22 21 Example 3 function min( int, int ) with 3-4 args? #include int min( int arg1, int arg2 ) { // min return arg1 < arg2 ? arg1 : arg2; } //end min int main( void ) { // main printf( “min of 2, -3 = %d\n”, min( 2, -3 ) ); printf( “min of 2, 12, 3 = %d\n”, min( 2, min( 12, 3 ) ) ); printf( “min of -9, 2, 12, 3 = %d\n”, min( min( -9, 2 ), min( 12, 3 ) ) ); return 0; } //end main

23 22 No parametersSingle parameterMultiple parameters (e.g., 2) No return value Declaration void fun (void); Declaration void fun (dtype a); Declaration void fun (dtype a, dtype b); Definition void fun (void) { /* return not needed */ } Definition void fun (dtype a) { /* return not needed */ } Definition void fun (dtype a, dtype b) { /* return not needed */ } Call fun(); Call fun(x); Call fun(x, y); Single return value Declaration dtype fun (void); Declaration dtype fun (dtype a); Declaration dtype fun (dtype a, dtype b); Definition dtype fun (void) { return expr; } Definition dtype fun (dtype a) { return expr; } Definition dtype fun (dtype a, dtype b) { return expr; } Call z = fun(); Call z = fun(x); Call z = fun(x, y);

24 23 Recursive Functions A function f() may call itself! Either directly, i.e. from inside its own body of f() Or indirectly, from inside another function g(), which was in turn called by f() The former is referred to as “directly recursive calls” The latter a “indirect recursive calls” Recursion is a powerful programming tool, so strong, it can replace almost all other tools; though that is not a recommended approach

25 24 Recursive Function Definition A function f() is recursive, if it is partly defined by simpler versions of f() itself The partly is important, providing for a base case, a case where the result is known and no further calls are made at all The simpler version is also important, else there would be no recursion at all, but instead infinite regress instead; that is as bad as an infinite loop Let’s see an example:

26 25 Simple Recursive Function: fact() #include // compute the unsigned factorial of an unsigned argument unsigned fact( unsigned arg ) { // fact if ( 0 == arg ) { return 1; }else{ return fact( arg – 1 ) * arg; } //end if } //end fact int main( void ) { // main int i; for ( i = 0; i < 10; i++ ) { printf( “fact(%d) = %d\n”, i, fact( i ) ); } //end for } //end main

27 26 Recursive Functions A But we shall not discuss recursion in more detail in a beginning course such as ECE 103


Download ppt "ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed."

Similar presentations


Ads by Google