0% found this document useful (0 votes)
5 views

Lec 7 - Functions

The document discusses functions in C programming, including defining, prototyping, and calling functions. It explains the components of functions such as return types, parameters, and passing arguments by value or reference. Examples are provided to illustrate function definitions and calls.

Uploaded by

nayyabkanwal2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lec 7 - Functions

The document discusses functions in C programming, including defining, prototyping, and calling functions. It explains the components of functions such as return types, parameters, and passing arguments by value or reference. Examples are provided to illustrate function definitions and calls.

Uploaded by

nayyabkanwal2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

CSC103 Programming Fundamentals

Lec 07: Functions


Introduction

➢ Real world problems are larger, more complex


➢ Top down approach
➢ Modularize – divide and conquer
➢ Easier to take smaller problems/module
➢ Repeated set of instructions

2
Divide and Conquer Approach

➢ Construct a program from smaller pieces or components


o Place smaller pieces into functions
➢ Pieces are more manageable than one big program
o Makes other functions smaller
o Pieces can be independently implemented and tested

3
Functions

➢ A function is a self-contained block of statements that


performs a coherent task of some kind.
➢ Functions allow us to
o Modularize a program
o Reuse the code
➢ Two types
o Programmer/user written, called programmer-defined
functions
o Prepackaged functions available in the standard C library

4
Example: Function

5
Modularizing a Program

➢ Analogy : Hierarchical management


➢ A boss (the calling function or caller) asks a worker (the
called function) to perform a task and report back when
the task is done.

7
Function

➢ The statements defining the function are written only


once, and the statements are hidden from other
functions.
➢ Functions are invoked by a function call, which specifies
the function name and provides information (as
arguments) that the called function needs to perform its
designated task.

8
Function

➢ All variables defined in function definitions are local


variables—they can be accessed only in the function in
which they’re defined.
➢ Most functions have a list of parameters that provide the
means for communicating information between
functions.
➢ A function’s parameters are also local variables of that
function.

9
Components of Function Use

➢ Three steps to implementing a function


1. Function declaration/prototype
▪ If not defined before use
2. Function definition
3. Function call
▪ Either prototype or definition must come first
➢ Prototype and/or definitions can go in either
o Same file as main()
o Separate file so other programs can also use it
• #include
10
Program Function Definition Structure

➢ main first (preferred)


o Top down design
o Some prototypes required
o Complete prototyping allows
function definition in any order
➢ main is last — lowest level
functions first
o Bottom up design
o Prototypes not required
➢ main in the middle
o Confusing — do not do!

11
1. Function Declaration/Prototype

➢ An ‘informational’ declaration for compiler


➢ Tells compiler how to interpret calls
➢ Syntax:
<return_type> FnName(<formal-parameter-list>);
➢ Formal parameter syntax:
<data_type> Parameter-Name
➢ Example
char grade(int score);

12
Function Declaration/Prototype

➢ Placed before any calls


o Generally above all functions in global space
o May be placed in declaration space of calling function
➢ Example

13
Alternative Function Declaration

➢ Function declaration is 'information' for compiler, so


o Compiler only needs to know
➢ Return type
➢ Function name
➢ Parameter list
➢ Formal parameter names not needed but help readability
➢ Example

14
2. Function Definition

➢ Actual implementation/code for what function does


o Just like implementing function main()
➢General format –header & basic block:
<return-type> fn-name (parameter-list)
basic block
➢ Example:

15
Example of User-defined Function

16
Function Definition

➢ Function square is invoked or called in main within the


printf statement
printf("%d ", square(x)); // function call
➢ Function square receives a copy of the value of x in the
parameter y.
➢ Then square calculates y*y.
➢ The result is passed back returned to function printf in
main where square was invoked, and printf displays
the result.
➢ This process is repeated 10 times using the for
statement.
17
Function Definition

➢ The definition of function square shows that square


expects an integer parameter y.
➢ The keyword int preceding the function name indicates
that square returns an integer result.
➢ The return statement in square passes the value of the
expression y*y (that is, the result of the calculation)
back to the calling function.
➢ int square(int y); // function prototype
▪ The int in parentheses informs the compiler that square
expects to receive an integer value from the caller.
▪ The int to the left of the function name square informs the
compiler that square returns an integer result to the caller.
18
Function Definition

➢ The compiler refers to the function prototype to check


that any calls to square contain
▪ the correct return type
▪ the correct number of arguments
▪ the correct argument types
▪ the arguments are in the correct order
➢ The function-name is any valid identifier.

▪ The int in parentheses informs the compiler that square


expects to receive an integer value from the caller.
▪ The int to the left of the function name square informs the
compiler that square returns an integer result to the caller.

19
Function Definition

➢ The return-value-type is the data type of the result returned


to the caller.
➢ The return-value-type void indicates that a function does not
return a value.
➢ Together, the return-value-type, function-name and
parameter-list are sometimes referred to as the function
header.

20
Function Definition

➢ The parameter-list is a comma-separated list that


specifies the parameters received by the function when
it’s called.
➢ If a function does not receive any values, parameter-
list is void.
➢ A type must be listed explicitly for each parameter.
➢ The definitions and statements within braces form the
function body, which is also referred to as a block.
➢ Variables can be declared in any block, and blocks can be
nested.

21
Return Type

➢ Returns control to calling function after function


execution
▪ the function does not return a result, control returns
immediately after the execution of function body
▪ returns after executing the statement return;
▪ returns the value of the expression to the caller by the
statement - return expression;

22
Return Statements

➢ Syntax: return return-value-expression


➢ Two actions
o Sets return value
o Transfers control back to 'calling' function
➢ Good programming & course requirement:
o One return per function
o Return is last statement

23
3. Function Call

➢ Using function name transfers control to function


1. Values are passed through parameters
2. Statements within function are executed
3. Control continues after the call
➢ For value-returning functions, either

24
Example 1

25
Example 2

26
Example 3

27
Example 3:

28
Example 4: gcd()

29
Example 4: gcd()

30
Parameters/Arguments

➢ Formal parameters
o In function declaration
o In function definition's header
o 'Placeholders' for data sent in
o 'Variable name' used to refer to
data in definition of function
➢ Actual arguments
o In function call
➢ X is formal parameter
➢ 5 is argument

31
Passing Arguments

➢ Arguments to a function can be passed by


o value or
o reference/pointer/address
➢ By default all arguments are passed by value in C

32
Passing Arguments: Passing by Value

➢ When we pass an argument to a function, function


makes a copy and works on that copy.
o The original argument value is unaffected.

33
Passing Arguments: Passing by Value

34
Passing Arguments: Passing by Value

➢ The function has a parameter x that takes the value of


the argument a.

➢ The function makes a copy of a and does not affect the


original a variable.

➢ The value of a remains the same before and after the


function call.

➢ The function makes temporary copies of a and works on


those copies, not the argument a itself.

35
Passing Arguments: Passing by
Reference/Pointer/Address

➢ To change the actual values of arguments a using a


function, we use the pointer type parameter in the
function signature.

➢ When we call the function, we supply the address of the


argument using an address-of operator &.

36
Passing Arguments: Passing by
Reference/Pointer/Address

37
Passing Arguments: Passing by Value &
Pointer

38
Passing Arguments: Passing by Value &
Pointer

39
Return Statement

40
Return Statement

41
Return Statement

42
Functions Calling Functions

➢ We're already doing this!


o main() is a function calling printf!
➢ Only requirement
o Function's declaration or definition must appear first
➢ Common for functions to call many other functions
o Function can call itself → Recursion

43
Declaring Void Functions

➢ Similar to functions returning a value


o Return type specified as 'void’
➢ Example prototype:
void showResults(double fDegrees, double cDegrees);
➢ Return-type is ‘void’

44
Declaring Void Functions

➢ Nothing is returned
o Void functions cannot have return statement with an
expression
▪ Will return at end of function
o Non-void functions must have return statement with an
expression
➢ Example definition:

45
Calling Void Functions

➢ From some other function, like main():


showResults(degreesF, DegreesC);
showResults(32.5,0.4);
➢ Cannot be used where a value is required
o Cannot be assigned to a variable, since no value returned

46
Calling Void Functions

47
Function Documentation

➢ Used to aid in program maintenance


➢ Comments at non-main definition header
o Purpose of function
o Parameters
o Return

48
Scope of Identifier Names

➢ Region of a program where identifier is visible


o Begins at definition within block
o Ends at end of block
➢ Local variables
o Name given to variables defined within function block
o Can have different local variables with same name declared
in different functions
o Cannot have duplicate local names within a function

49
Scope of Identifier Names

➢ Local variables preferred


o Maintain individual control over data
o Functions should declare whatever local data needed to
'do their job'

50
Global Scope

➢ Names declared 'outside' function bodies


o Global to all functions in that file
➢ Global declarations typical for constants:
o Declare globally so all functions have scope, can use

51
Global Constants and Global Variables

➢ Global variables?
o Possible, but SELDOM-USED
o Better alternative is to use parameters
o Dangerous: no control over usage!

52
Block Scope

➢ Declare data inside nested blocks


o Has 'block-scope’
o Note: All function definitions are blocks!

53
Lifetime

➢ How long does it last


o Allocation → Deallocation
o Normally variables are allocated when defined
o Normally variables are deallocated at the end of block

54
Static & Lifetime

➢ Variable definition modifier keyword: static


➢ Static variables are only allocated once
➢ Static variables are not deallocated until program ends

55
Math Library Functions

56
More Math Library Functions

57

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy