C Pointer and Functions - PowerPoint PPT Presentation

1 / 70
About This Presentation
Title:

C Pointer and Functions

Description:

Two types of values are associated with a variable. l-value : the address value of the variable. ... int main(int argc, char *argv[]) 26. Parameter Type Checking ... – PowerPoint PPT presentation

Number of Views:94
Avg rating:3.0/5.0
Slides: 71
Provided by: gg13
Category:

less

Transcript and Presenter's Notes

Title: C Pointer and Functions


1
SECTION 3
  • C Pointer and Functions

2
L-value and R-value
  • L-Value and R-Value
  • Two types of values are associated with a
    variable.
  • l-value the address value of the variable.
  • r-value the real value of the variable.
  • The left hand side of an assignment operator
  • requires an l-value.

3
L-value and R-value
  • Example
  • int x 10,
  • y 20
  • x y // r-value of y is stored in the l-value
    of x
  • y x // r-value of x is stored in the l-value
    of y
  • x 1 // r-value of literal constant 1 is stored
    in the
  • // l-value of x
  • 1 y // error. no l-value for literal constant
    1.
  • x // xx1
  • 10 // ?

4
Pointer definition
  • Syntax
  • base type pointer name
  • where base type defines the type of variable the
  • pointer points to.
  • Example
  • int ptr1 // a pointer to integer.
  • int ptr2 // a pointer to pointer to integer
  • int ptr1, ptr2 // a pointer and an integer

5
Figure of Memory Allocation
  • dynamic objects
    memory managed by

  • programmerby
    explicitly

  • call of
    new/delete
  • Function parameters,
  • Local objects
    memory managed by

  • compiler
    used for each

  • function
    call
  • global objects
    global dataobject locations

  • are fixed
    value but can be

  • changed
  • Function definitions code and
    read-only
  • objects

6
Memory Allocation
  • In C, operator new and delete are used to
    allocate and free storage dynamically.
  • int main()
  • int ptr1
  • float ptr2
  • ptr1 new int
  • // In C ptr1malloc (sizeof(int))
  • ptr2 new float
  • // In C ptr2malloc (sizeof(float))
  • ptr1 20
  • ptr2 13.5
  • delete ptr1
  • // In C free(ptr1)
  • delete ptr2

7
Memory Allocation
8
Dynamic Arrays
  • Example
  • int main()
  • float a
  • int n
  • cout ltlt enter size of list''
  • cin gtgt n
  • a new float n
  • // C code a malloc(n sizeof(float))
  • for(int i0 iltn i)
  • cin gtgt ai
  • delete a

9
Dynamic Arrays
Use delete when the dynamic object is an array.
10
Dynamic Allocation ofMulti-dimensional Array
Example include ltiostreamgt using namespace
std int main() int m,n cout ltlt enter the
number of rows and columns ''ltlt'\n' cin gtgt m gtgt
n int a //a is a pointer to pointer to
integer a new intm //a points to an array
of integer pointer
//the size of this pointer array is m
11
Dynamic Allocation ofMulti-dimensional Array
for(int i0 iltm i) //each pointer in the
array points to ai new intn
//an array of integer
//the size of these integer arrays is
n cout ltlt''Enter values for this
''ltltmltlt''by''ltltnltlt''array\n'' for(int i0 iltm
i) for(int j0 jltn j) cin gtgt
aij for (int i0 iltm i) //deallocate
memory delete ai delete a
12
Dynamic Allocation ofMulti-dimensional Array
13
Dynamic Allocation of Multi-dimensional Array
14
Dynamic Allocation of Multi-dimensional Array
  • Note
  • In C, new, new, delete, delete are built-in
    operators
  • rather than library functions.
  • new, new, delete, delete should be used
    together, and not mixed with C storage
    management functions (malloc, free).
  • Programmer should explicitly deallocate the
    memory of
  • dynamic objects.

15
Dynamic Allocation of Multi-dimensional Array
Related problems memory leak dangling
pointer
16
Dynamic Memory Allocation
  • Questions
  • Does the statement
  • delete ptr
  • delete the pointer ptr or the object being
    referred by ptr?

17
C Reference Type
  • In C, reference type provides an alternative
    name for an object. The definition of a reference
    is preceded by the operator.
  • Example
  • int x 10
  • int ref1 x // ref1 is a reference to int x.
  • int ref2 ptr // ref2 is a reference to int
    pointer ptr.
  • A reference is a name alias - Not a pointer !

18
C Reference Type
  • The main use of reference is for specifying
    arguments and return values for functions in
    general and for overloaded operators in
    particular.
  • When a reference is defined, it must be
    initialized to an object.
  • Once initialized, a reference can not be
    reassigned to refer to another object.

19
C Reference Type
  • Example //sam7.cpp
  • int a, b5
  • int ref a // a and ref both
    refer to same memory location!
  • // ref is an
    alias for a
  • a 3
  • ref 3 // both affect a
  • ref b //ref5
  • ref //ref6
  • //Compared to pointer
  • int ptr // ptr is a new object
  • ptr a
  • ptr 3
  • ptr b // ok

20
C Reference Type
  • Reference types are usually used as function
  • parameters. It can
  • increase code clarity,
  • reduce function parameter costs,
  • optimize compilation.

21
C Reference Type
  • A reference is just an alias, its different from
    pointer.
  • Some differences between a reference and a
    pointer
  • A reference cannot be NULL
  • Once established a reference cannot be changed
  • An alias does not need dereferencing
  • A reference is declared by using the ampersand
  • All operators operate on the actual value not
    reference

22
C Reference Type
  • The most common use of reference is pass by
    reference to a function (allowing the function to
    change the actual value)
  • Example
  • include ltiostreamgt
  • void passExample ( int i ) i i i 1
  • int main ()
  • int j 5
  • passExample(j)
  • cout ltlt j ltlt endl return 0

23
Functions in C
  • A function declaration ( function prototype )
    consists of the function name, its return type,
    and the number and types of the function
    parameters.
  • Example
  • int f(int, int) // declaration of f
  • // f has two integer parameters
  • // and returns a integer
  • void g() // declaration of g
  • // g has no argument and returns nothing

24
Functions in C
  • A function body or function block is the function
    implementation enclosed in braces.
  • A function definition is composed of the function
    declaration and the function body.
  • Actual parameters arguments provided at the
    function call they are placed inside the call
    operator.
  • Formal parameters parameters received by the
    function definition.
  • A function is evaluated when the function name is
    followed by the call operator ( ).

25
Functions in C
  • Note
  • C is a strongly typed language. A function
    cannot be called unless it is previously
    declared.
  • The following two prototypes of main are
    supported by all C compilers.
  • int main()
  • int main(int argc, char argv)

26
Parameter Type Checking
  • The arguments of every function call are
    type-checked during compilation. If there is a
    type mismatch, implicit conversion is applied if
    possible.
  • //sam8.cpp
  • void f( int ) / ... /
  • int x 0
  • bool flag true
  • char c 'a'
  • f( 10 ) // exact
    match
  • f( x ) //
    exact match
  • f( flag ) // match
    with a promotion
  • f( c ) // match
    with a promotion
  • f( 12.34 ) // match
    with a standard conversion
  • f( "hello" ) // mismatch
  • f( 12, 3 ) // mismatch

27
Call by Value
  • The default argument passing method in C is
    call by value.
  • Example
  • void f(int x)
  • int main()
  • int a 10
  • f(a)
  • f(10)
  • void f(int x)
  • x 100

28
Call by Value
  • During the first function call to f()
  • a is the actual parameter x is the formal
    parameter
  • Because a is passed by value, its content is
    copied to the functions parameter x
  • x and a are physically two different memory cells

29
Call by Value
30
Call by Value
31
Call by Reference
  • Call by reference can be simulated by using
    pointer and address passing.
  • Example
  • void swap(int a, int b)
  • int main()
  • int x 1
  • int y 2
  • swap(x, y)

32
Call by Reference
  • void swap( int a, int b)
  • int tmp
  • tmp a
  • a b
  • b tmp

33
Call by Reference
  • The reference operator is usually used to specify
    a call-by-reference parameter in C.
  • Example 1 //sam9.cpp
  • void f(int a, int b)
  • int main()
  • int i 0
  • int j 0
  • f(i, j)
  • cout ltlt i ltlt'\n' //i0
  • cout ltlt j ltlt'\n' //j1
  • void f(int a, int b)
  • a
  • b

34
Call by Reference
  • Example 2
  • void swap(int a, int b)
  • int main()
  • int x 1
  • int y 2
  • swap(x, y)
  • void swap(int a, int b)
  • int tmp
  • tmp a // not tmp a !
  • a b
  • b tmp

35
Call by Reference
36
Return by Value
  • When a function returns an object by value, the
    value to be returned is copied to a temporary
    storage before the function call ends, so the
    calling function can access the value.
  • Example
  • int f(int x)
  • x xx - 100
  • return x
  • int main()
  • int y f(10)

37
Return by Value
38
Return by Reference
  • When a function returns an object by reference
  • using reference operator (), the object is
    returned
  • as l-value.
  • Example //sam10.cpp
  • int f( int ptr, int x )
  • return ptrx
  • int main()
  • int a100
  • coutltltf( a, 10 )ltltendl

39
Return by Reference
  • A local object should not be returned by
    reference since the lifetime of local object ends
    when the function call finishes.
  • Example
  • int add(int x, int y)
  • int result x y
  • return result // error

40
Array Parameters
  • When an array is used as a function argument, the
    address of the array is passed.
  • Example //sam11.cpp
  • void display(int num10, int size)
  • int main()
  • int a10
  • for(int i0 iltsize i)
  • ai i
  • display(a, 10)
  • void display(int num10, int size)
  • for (int i0 iltsize i)
  • coutltlt numi ltlt'\n'

41
Array Parameters
  • Three equivalent declarations of display
  • void display(int num10, int size)
  • void display(int num, int size)
  • void display(int num, int size)
  • The function call display(a, 10) is an exact
    match of any of the above declarations.

42
Array Parameters
  • To avoid modifying the local copy of array
    elements, we can use the const specifier.
  • void display(const int num, int size)
  • // ...

43
Array Parameters
  • Since an array is passed as a pointer, the size
    of the array is not known in the function called.
  • Example
  • void display( int num10 )
  • int main()
  • int i, j2
  • display( i ) // ok i is type
    int
  • display( j ) // j is type int
  • // but,
    potential run-time error

44
Default Argument
  • In C, default values can be specified for
    function parameters, so the function can be
    called without being provided all the arguments.
  • Example
  • void f( int x, double m12.34 )
  • int main()
  • f( 1, 1234.56 ) // ok
  • f( 1 ) // ok, m12.34
  • f() // error! no default value for x

45
Default Argument
  • Default arguments can be provided by trailing
    arguments only.
  • void f( int x1, double m, char s'a') // wrong
  • void f( int x1, double m12.34, char s) //
    wrong
  • void f( int x, double m, char s'a') // ok

46
Default Argument
  • Default arguments should be supplied in a
    function declaration, not in a function
    definition.
  • Example
  • // file f.h
  • void f(int, int)
  • // file f.cpp
  • void f( int a 2, int b 3)
  • // ...

47
Default Argument
  • Correct version
  • // file f.h
  • void f(int a 2, int b 3)
  • // also ok void f(int 2
    , int 3)
  • // file f.cpp
  • void f( int a, int b)
  • //...

48
Default Argument
  • For a previously defined function, additional
    default arguments can be specified using
    succeeding declarations. Thus, a general function
    can be customized for a more specific use.
  • Example
  • The UNIX system library function chmod() changes
    the protection level of a file. It is declared
    as
  • int chmod( char filePath, int protMode )

49
Default Argument
  • chmod() can be redeclared to supply the
    protection mode value a default value of
    read-only.
  • include ltcstdlibgt
  • int chmod( char filePath, int protMode 0444 )

50
Scope and Lifetime
  • Two questions
  • How long does the object exist
    lifetime
  • The life time of a C object is either static,
    automatic, or dynamic. This is referred to as the
    storage class of an object.
  • Where the object can be used
    scope
  • C supports local scope, namespace scope and
    class scope.

51
Object Lifetime
Dynamic object
objects live until it is
destroyed
by programmer
using "delete"
function parameters,
object live until the end Local objects
of function
call or local
scope
Global objects
object live for the entire

execution of program
Function definitions
objects (literal constant)
live
for the entire execution
of program
52
Local Scope and Local Objects
  • A local scope is the program text enclosed in
  • braces . Each function block represents a
  • distinct local scope.
  • An object declared in local scope is a local
    object
  • to the block.
  • A local object can be
  • Automatic object
  • Static local object

53
Local Scope and Local Objects
  • An automatic object has its storage allocated
    when the block is entered, and its storage
    deallocated when the block ends.
  • Example
  • void f(int, int)
  • int main() // in scope of main
  • int x 1, y 2
  • f( x, y )
  • int x // nested scopes
  • void f(int a, int b) // in scope of f()
  • int tmp
  • tmp a b

54
Static Local Objects
  • A local object with static specifier. Static
    objects persist for the entire duration of the
    program.

55
Static Local Objects
  • Example
  • void f()
  • int main()
  • f() f() f()
  • void f()
  • static int i // initialized to 0 by default
  • int x 0
  • cout ltlt''i '' ltlt i ltlt''x '' ltlt x ltlt'\n'
  • i i1
  • x x1
  • What is the output?

56
Static Local Objects
  • Note
  • The word static has double meaning in C
  • 1. regarding memory allocation.
  • 2. regarding scope of variable.

57
Dynamically Allocated Objects
  • A dynamically allocated object is created by the
    programmer using a new expression, and terminated
    by user with a delete.
  • Example
  • int f()
  • int ptr new int
  • return ptr
  • int main()
  • int ptr
  • ptr f()
  • delete ptr
  • // ...

58
Function Overloading
  • In C, functions can be overloaded if they have
  • the same name, declared in the same scope and
  • have different signatures.
  • The signature of a function consists of
    the number, data types and order of the
    functions parameter list.
  • Function overloading is a form of polymorphism.

59
Function Overloading
  • Functions must have distinct signatures to be
  • overloaded.
  • Example
  • void f1(int)
  • void f1(double)
  • void f2(int)
  • void f2(int, int)
  • void f3(int, double)
  • void f3(double, int)

60
Function Overloading
  • Functions must have distinct signatures to be
    overloaded.
  • Example
  • void f4(int, double) // ok?
  • int f4(int, double)
  • void f5( char ) // ok?
  • void f5( char )
  • void f6( int ) // ok?
  • void f6( const int )

61
Function Overloading Resolution
  • A function call is associated with one function
    in a set of overloaded functions through the
    process of function overload resolution.

62
Function Overloading Resolution
  • The 3 steps of overloaded function resolution.
  • Find candidate functions functions that match
  • the name.
  • 2. Find viable functions functions that can be
    called
  • from the candidate function list.
  • 3. Find the best viable function the best match,
    if
  • the exact match is not available.
  • If no best match found, then the function call is
  • ambiguous.

63
Function Overloading Resolution
  • Exercise Which f()will be called?
  • void f()
  • void f( int )
  • void f( double, double 12.34 )
  • void f( char, char )
  • int main()
  • f( 56.78 )

64
Inline Function
  • In many programming languages, programmers
  • have to choice between
  • Abstraction/modularity( function call )
  • Performance( macro or inline-expansion by hand )
  • Functions good abstraction but introduce
    overhead at run-time.
  • C macro efficient but problematic.

65
Inline Function
  • Example
  • define SQUARE(X) ( (X) (X) )
  • int a SQUARE(10) // expanded by
    preprocessor to
  • //
    int a 10 10
  • int x SQUARE(a) // problem here
    expanded to
  • // int
    x (a) (a)

66
Inline Function
  • An inline function is a function that is expanded
  • at the point of the function call at compilation
    time rather than actually being executed at
    run-time.
  • Consider the function max()
  • inline int max( int x, int y )
  • return( x gt y ? x y )

67
Inline Function
  • so the code
  • int Max max( a, b )
  • may be expanded during compilation as
  • int Max ( a gt b ? a b )
  • Using inline functions avoids the overhead of
  • function calls, while preserves the benefits of
  • abstraction.

68
Pointer to Functions
  • In C/C, pointers to function can be declared
  • to store the address of a function.
  • double f1(double x )
  • double f2(double x )
  • int f3()
  • double (fptr)(double) // fptr is a
    pointer to function which
  • //
    takes a double and returns a double
  • fptr f1 // ok
  • fptr f2 // ok
  • fptr f3 // wrong
  • result (fptr)( 12.34 ) // ok
  • result fptr( 12.34) // ok

69
Functions as Arguments
  • Functions can be passed as arguments into another
    function through function pointers.
  • Example
  • include ltiostreamgt
  • using namespace std
  • void plot(double (fptr)(double), double, double,
    int)
  • double f1(double x )
  • double f2(double x )
  • int main()
  • cout ltlt "Mapping first function" ltlt endl
  • plot( f1, 0, 0.1, 50)
  • cout ltlt "Mapping second function" ltlt endl
  • plot( f2, 0.1, 0.5, 50)

70
Functions as Arguments
  • void plot(double (fptr)(double), double x0,
    double incr, int n)
  • for ( int i0 iltn i)
  • cout ltlt " x " ltlt x0
  • ltlt " (fptr)(x) " ltlt (fptr)(x0) ltlt endl
  • x0 incr
  • double f1( double x ) return x2
  • double f2( double x ) return x3-2
Write a Comment
User Comments (0)
About PowerShow.com