0% found this document useful (0 votes)
72 views46 pages

Functions PDF

The document discusses C functions and related concepts like function definitions, function prototypes, function call stacks, passing arguments, and headers. It defines what a function is and explains that functions allow dividing programs into smaller, more manageable pieces. It covers the syntax of function definitions and prototypes. It also describes how function calls are handled via the function call stack and stack frames. Examples are provided to illustrate functions and passing arguments. The document concludes with a brief overview of headers and the #include directive.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views46 pages

Functions PDF

The document discusses C functions and related concepts like function definitions, function prototypes, function call stacks, passing arguments, and headers. It defines what a function is and explains that functions allow dividing programs into smaller, more manageable pieces. It covers the syntax of function definitions and prototypes. It also describes how function calls are handled via the function call stack and stack frames. Examples are provided to illustrate functions and passing arguments. The document concludes with a brief overview of headers and the #include directive.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

C Functions

Computer Programming I

Carlos Alberto Hinojosa Montero


July 12, 2016
Universidad Industrial de Santander
Table of contents

1. Introduction

2. Functions

3. Function Call Stack and Stack Frames

4. Example

5. Headers

6. Passing Arguments By Value and By Reference

7. Storage Classes

8. Recursion
1
Introduction
Introduction

• The best way to develop and maintain a large program is to


construct it from smaller pieces or modules, each of which is more
manageable than the original program.

Divide and Conquer

• Modules in C are called functions.


• The C standard library provides a rich collection of functions for
performing common mathematical calculations, string
manipulations, character manipulations, input/output, and many
other useful operations.
• The functions printf, scanf and pow are standard library functions.

2
Introduction

Motivations for “functionalizing” a program


• The divide-and-conquer approach makes program development more
manageable.
• software reusability. Use existing functions as building blocks to
create new programs.
• Avoid repeating code in a program.

3
Introduction

Observations
• Familiarize yourself with the rich collection of functions in the C
standard library.
• Avoid reinventing the wheel. When possible, use C standard library
functions instead of writing new functions. This can reduce program
development time.
• Using the functions in the C standard library helps make programs
more portable.
• Each function should be limited to performing a single,
well-defined task, and the function name should express the task.
• If you cannot choose a concise name that expresses what the
function does, it’s possible that your function is attempting to
perform too many diverse tasks. It’s usually best to break such a
function into several smaller functions.

4
Functions
Functions

Function Definition

r e tu r n_v a l u e _ t y p e function_name ( paramete r_list )


{
definitions
statements

return expression ; // only if the r e t u r n _ v a l u e _ t y p e


// is not void
}

• The function body is also referred to as a block.


• All variables defined in function definitions are local variables - they
can be accessed only in the function in which they’re defined.
• The list of parameters provide the means for communicating
information between functions. A function’s parameters are also
local variables of that function.
• The return-value-type void indicates that a function does not return
a value. 5
Functions

• If the function does not return a result, control is returned simply


when the function-ending right brace is reached, or by executing the
statement
return ;

• If the function does return a result, the statement


return expression ;

returns the value of expression to the caller. The type of expression


must match the return-value-type.
• The return value of main is used to indicate whether the program
executed correctly.
return 0;

at the end of main - 0 indicates that a program ran successfully. You


can explicitly return non-zero values from main to indicate that a
problem occurred during your program’s execution.
6
Functions

Example

1 // F u n c t i o n maximum d e f i n i t i o n
2 // x , y and z are p a r a m e t e r s
3 int maximum ( int x , int y , int z )
4 {
5 int max = x ; // assume x is largest
6

7 if ( y > max ) { // if y is larger than max ,


8 max = y ; // assign y to max
9 } // end if
10

11 if ( z > max ) { // if z is larger than max ,


12 max = z ; // assign z to max
13 } // end if
14

15 return max ; // max is largest value


16

17 } // end f u n c t i o n maximum

7
Functions

Function Prototype

r e tu r n_v a l u e _ t y p e function_name ( paramete r_list ) ;

• The compiler uses function prototypes to validate function calls.

Example

int maximum ( int x , int y , int z ) ; // F u n c t i o n p r o t o t y p e

It states that maximum takes three arguments of type int and returns a
result of type int.

• Parameter names are sometimes included in function prototypes for


documentation proposes. The compiler ignores these names.
• A function call that does not match the function prototype is a
compilation error. An error is also generated if the function
prototype and the function definition disagree. 8
Functions

Argument Coercion
• In general, argument values that do no correspond precisely to the
parameter types in the function prototype are converted to the
proper type before the function is called. These conversions can lead
to incorrect results if C’s usual arithmetic conversion rules are not
followed.
printf ( " %.3 f \ n " , sqrt (4) ) ;

• What happens if our function accepts integers as argument and we


insert a double ?

9
Functions

• Mixed-type expressions
int b = 3 + 4.67

Arithmetic conversion rules


• If one of the values is a long double, the other is converted to a long
double.
• if one of the values is a double, the other is converted to a double.
• If one of the values is a float, the other is converted to a float.

10
Functions

11
Functions

12
Function Call Stack and Stack
Frames
Function Call Stack and Stack Frames

• A stack is a last-in, first-out (LIFO) data


structures. The last item pushed (inserted) on
the stack is the first item popped (removed) from
the stack.
• Think of a stack as analogous to a pile of dishes.
• The Function call stack is the data structure that
supports the function call/return mechanism.
• Each time a function calls another function, an
entry is pushed onto the stack. This entry, called
a stack frame, contains the return address that
the called function needs in order to return to the
calling function. It also contains some additional
information.
• If the called function returns, the stack frame for
the function call is popped, and control transfers
to the return address in the popped stack frame.
13
Function Call Stack and Stack Frames

14
Function Call Stack and Stack Frames

15
Function Call Stack and Stack Frames

16
Function Call Stack and Stack Frames

17
Example
Example

1 // Finding the maximum of three i n t e g e r s .


2

3 int maximum ( int x , int y , int z ) ; // f u n c t i o n p r o t o t y p e


4

5 // f u n c t i o n main begins program e x e c u t i o n


6 int main ( void )
7 {
8 int number1 ; // first integer entered by the user
9 int number2 ; // second integer entered by the user
10 int number3 ; // third integer entered by the user
11

12 printf ( " % s " ," Enter three integers : " ) ;


13 scanf ( " % d % d % d " , & number1 , & number2 , & number3 ) ;
14

15 // number1 , number2 and number3 are a r g u m e n t s


16 // to maximum f u n c t i o n call
17 printf ( " Maximum is : % d \ n " , maximum ( number1 , number2 ,
number3 ) ) ;
18 } // end main
18
Example

1 // F u n c t i o n maximum d e f i n i t i o n
2 // x , y and z are p a r a m e t e r s
3

4 int maximum ( int x , int y , int z )


5 {
6 int max = x ; // assume x is largest
7

8 if ( y > max ) { // if y is larger than max ,


9 max = y ; // assign y to max
10 } // end if
11

12 if ( z > max ) { // if z is larger than max


13 max = z ; // assign z to max
14 } // end if
15

16 return max ; // max is largest value


17 } // end f u n c t i o n maximum

19
Headers
Headers

20
Headers

• A header contains function prototypes and definitions of various


data types and constants needed by those functions.
• The C preprocessor executes before a program is compiled.
• The #include preprocessor directive causes a copy of a specified file
to be included in place of the directive.
• The two forms of the #include directive are:
# include < filename >
# include " filename "

The difference between these is the location at which the


preprocessor begins searches for the file to be included.

21
Headers

• The #define directive creates symbolic constants - constants


represented as symbols - and macros - operations defined as
symbols. The #define directive format is
# define identifier replacement - text

Example:
# define PI 3.14159

However, better use


const double PI = 3.14159

• Example of a macro definition with one argument for the area of a


circle:
1 # define CIRCLE_AREA ( x ) ( ( PI ) * ( x ) * ( x ) )

Wherever CIRCLE AREA(y) appears in the file, the value y is


substituted for x in the replacement-text and the symbolic constant
PI is replaced by its value (defined previously). Better use functions! 22
Headers Example

File 1: myformula.h

1 # ifndef MYFORMULA_H
2 # define MYFORMULA_H
3

4 # include < math .h >


5 # include < stdio .h >
6 # include < stdbool .h >
7

8 double expSquare ( double num , bool print ) ;


9

10 # endif // M Y F O R M U L A _ H

23
Headers Example

Listing 2: myformula.c

1 # include " myformula . h "


2

3 double expSquare ( double num , bool print ) {


4

5 double result = sqrt ( exp ( num ) ) ;


6 if ( print ==1) {
7 printf ( " The result is %0.4 f \ n " , result ) ;
8 }
9

10 return result ;
11 }

24
Headers Example

Listing 3: main.cpp

1 # include " myformula . h "


2

3 int main () {
4

5 double num ;
6 printf ( " Ingrese un numero : " ) ;
7 scanf ( " % lf " , & num ) ;
8 expSquare ( num ,1) ;
9

10 return 0; // main ends without errors


11

12 }

25
Passing Arguments By Value and
By Reference
Passing Arguments By Value

• When arguments are passed by value, a copy of the argument’s vale


is made and passed to the called function.
• Changes to the copy do not affect an original variable’s value in the
caller.
• Pass-by-value should be used whenever the called function does not
need to modify the value of the caller’s original variable. This
prevents accidental variable modifications.
• Example:

int main () {

double num ;
printf ( " Ingrese un numero : " ) ;
scanf ( " % lf " , & num ) ;
expSquare ( num ,1) ; // num is passed by value

return 0; // main ends without errors


}
26
Passing Arguments By Reference

• When an argument is passed by reference, the caller allows the


called function to modify the original variable’s value.
• Pass-by-reference should be used only with trusted called functions
that need to modify the original variable.
• Example:

int main () {

double num ;
printf ( " Ingrese un numero : " ) ;
scanf ( " % lf " , & num ) ; // num is passed by r e f e r e n c e
expSquare ( num ,1) ;

return 0; // main ends without errors


}

27
Storage Classes
Storage Classes

• An identifier’s storage class determines its storage duration, scope


and linkage. C provides the storage classes: auto, register, extern
and static.
• An identifier’s storage duration is the period during which the
identifier exists in memory.
• An identifier’s scope is where the identifier can be referenced in a
program.
• An identifier’s linkage determines for a multiple-source-file program
whether the identifier is known only in the current source file or in
any source file with proper declarations.
• Local variables have automatic (auto) storage duration. This
variables are created when the block in which they’re defined is
entered; they exist while the block is active, and they’re destroyed
when the block is exited.

28
Storage Classes

• Keywords extern and static are used in the declarations of


identifiers for variables and functions of static storage duration.
Identifiers of static storage duration exists from the time at which
the program begins execution until the program terminates.
• For static variables, storage is allocated and initialized only once,
before the program begins execution.
• Storage duration and scope(where a name can be used) are separate
issues. This is very important!.
• Local variables declared with the keyword static are still known only
in the function in which they’re defined. Static local variables retain
their value when the function is exited.
• The next time the function is called, the static local variable
contains the value it had when the function last exited.
• All numeric variables of static storage duration are initialized to zero
by default if you do not explicitly initialize them.
29
Static - Example

1 # include < stdio .h >


2

3 int accumulateSum () ; // f u n c t i o n p r o t o t y p e
4

5 int main ( void )


6 {
7 for ( int i =0; i <10; i ++) {
8 printf ( " The actual sum is % d \ n " , accumulateSum () ) ;
9 }
10 return 0;
11 }
12

13 int accumulateSum () {
14 // because the static keyword , sum is created
15 // only once . The default value is 0.
16 static int sum ;
17 // e v e r y t i m e we access the function ,
18 // sum i n c r e a s e s it value by 1.
19 sum = sum +1;
20 return sum ;
21 } 30
Storage Classes

• extern keyword is used to extend the visibility of variables/functions.


• Global variables and function names are of storage class extern by
default.
• Global variables and functions can be referenced by any function
that follows their declarations or definitions in the file.
• When extern is used with a variable, it’s only declared not defined.
Declaration can be done any number of times but definition only
once.
• As an exception, when an extern variable is declared with
initialization, it is taken as definition of the variable as well 1 .

1 http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

31
Scope Rules

• The scope of an identifier is the portion of the program in which


the identifier can be referenced.
• The four identifier scopes are function scope, file scope, block scope,
and function-prototype scope.
• An identifier declared outside any function has file scope. Global
variables, function definitions, and function prototypes placed
outside a function all have file scope.
• Identifiers defined inside a block have block scope. Block scope
ends at the terminating right brace (}) of the block.
• Local variables defined at the beginning of a function have block
scope, as do function parameters, which are considered local
variables by the function.
• When blocks are nested, and an identifier in an outer block has the
same as an identifier in an inner block, the identifier in the outer
block is hidden until the inner block terminates.
• Local variables declared static still have block scope.
32
Recursion
Recursion

A recursive function is a function that calls itself either directly or


indirectly through another function.

• The function actually knows how to solve only the simplest case(s),
or so-called base case(s). If the function is called with a base case,
the function simply returns a result.
• If the function is called with a more complex problem, the function
divides the problem intro two conceptual pieces: a piece that the
function knows how to do and a piece that it does not know how to
do. This is called the recursion step.
• For the recursion to terminate, each time the function calls itself
with a slightly simpler version of the original problem, this sequence
of smaller problems must eventually converge on the base case.
• When the function recognizes the base case, it returns a result to
the previous copy of the function, and a sequence of returns ensues
all the way up the line until the original call of the function
eventually returns the final result to main.
33
Recursion - Example - Factorial

1 // R e c u r s i v e f a c t o r i a l f u n c t i o n
2 # include < stdio .h >
3

4 unsigned long long int factorial ( unsigned int number ) ;


5

6 // f u n c t i o n main begins program e x e c u t i o n


7

8 int main ( void )


9 {
10 unsigned int i ; // counter
11 // during each iteration , c a l c u l a t e
12 // f a c t o r i a l ( i ) and display result
13 for ( i = 0; i <= 21; ++ i ) {
14 printf ( " % u ! = % llu \ n " , i , factorial ( i ) ) ;
15 } // end for
16

17 } // end main

34
Recursion - Example - Factorial

1 unsigned long long int factorial ( unsigned int number )


2 {
3 // base case
4 if ( number <= 1 ) {
5 return 1;
6 } // end if
7 else {
8 return ( number * factorial ( number - 1 ) ) ;
9 } // end else
10 } // end f u n c t i o n f a c t o r i a l

35
Recursion - Example - Factorial

36
Recursion - Example - Factorial

37

You might also like