1 / 27

ECE 103 Engineering Programming Chapter 30 C Functions

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. Syllabus. Introduction Function Definition Parameter List Function Body

quinta
Download Presentation

ECE 103 Engineering Programming Chapter 30 C Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ECE 103 Engineering ProgrammingChapter 30C 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. 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 2

  4. 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 Return Value Arguments 3

  5. 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 ) ); 4

  6. 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 5

  7. 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 6

  8. 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. 7

  9. 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 call '#' 42 5 3 Function definition 8

  10. 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 */ 9

  11. 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!! 10

  12. 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 ); } 11

  13. 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! 12

  14. Example: /* Program #1 Compute areas of triangles - without separate function */ #include <stdio.h> 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 13

  15. Example: /* Program #2 Compute areas of triangles – with function */ #include <stdio.h> 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 14

  16. 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 15

  17. 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: Top of source file C B D A 16

  18. 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 1st since both fun2 and main call it. fun2 defined 2nd since main calls it (but not fun1). main defined last 17

  19. 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 18

  20. Example 1, with formal parameter names: #include <stdio.h> /* 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. 19

  21. Example 2 without formal parameter names: #include <stdio.h> /* 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 20

  22. Example 3 function min( int, int ) with 3-4 args? #include <stdio.h> 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 21

  23. 22

  24. 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 23

  25. 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: 24

  26. Simple Recursive Function: fact() #include <stdio.h> // 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 25

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

More Related