Using C Functions - PowerPoint PPT Presentation

1 / 45
About This Presentation
Title:

Using C Functions

Description:

How to construct function headers and prototypes ... How to use classes and objects as arguments to functions and as return types of functions ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 46
Provided by: informatio100
Category:
Tags: construct | functions | how | to | using

less

Transcript and Presenter's Notes

Title: Using C Functions


1
Using C Functions
4
  • Object-Oriented Programming Using C
  • Second Edition

2
Objectives
4
  • Review
  • About using function as a procedural abstraction
  • About scope rules
  • How to construct function headers and prototypes
  • How to return values from, and pass values to
    functions
  • In this lecture, you will learn
  • How to use classes and objects as arguments to
    functions and as return types of functions

3
Objectives
4
  • You will learn
  • How to pass addresses to functions
  • How to use reference variables
  • How to pass arrays to functions
  • How to use inline functions
  • How to use default arguments
  • How to overload functions

4
Using Functions and Include Files
4
  • Functions are modules that perform a task or
    group of tasks
  • In other programming languages, the counterpart
    to a function is known as a subroutine,
    procedure, or method
  • You can write new C functions, and you can use
    functions that other programmers have written
  • Any statement allowed in the main( ) function of
    a C program can be used in any other function

5
Understanding Scope
4
  • Some variables can be accessed throughout an
    entire program, while others can be accessed only
    in a limited part of the program
  • The scope of a variable defines where it can be
    accessed in a program
  • To adequately understand scope, you must be able
    to distinguish between local and global variables

6
Distinguishing Between Local and Global Variables
4
  • Celebrity names are global because they are known
    to people everywhere and always refer to those
    same celebrities
  • Global variables are those that are known to all
    functions in a program
  • Some named objects in your life are local
  • You might have a local co-worker whose name takes
    precedence over, or overrides, a global one

7
Distinguishing Between Local and Global Variables
4
  • Variables that are declared in a block are local
    to that block and have the following
    characteristics
  • Local variables are created when they are
    declared within a block
  • Local variables are known only to that block
  • Local variables cease to exist when their block
    ends
  • Variables declared within a function remain local
    to that function
  • In contrast, variables declared within curly
    braces within any function are local to that block

8
Using the Scope Resolution Operator
4
  • Each programmer can use x as a variable name
    without destroying any values in the others
    function
  • A major advantage of using local variables is
    that many programmers can work on a large
    program, each writing separate functions, and
    they can use any variable names inside their own
    functions
  • If you choose to create a global variable, you
    can use it even when a local variable with the
    same name exists

9
Using the Scope Resolution Operator
4
  • To do so, you use the scope resolution operator
  • Place this operator (the symbol ) directly
    before the variable name
  • Although you can declare global variables in any
    file, it is almost always considered better style
    to use local variables rather than global ones

10
Using the Scope Resolution Operator
4
  • This strategy represents a preliminary example of
    encapsulation, or data hiding
  • Using global variables, rather than creating
    local variables in functions, is actually
    disadvantageous for the following reasons
  • If variables are global in a file and you reuse
    any functions in a new program, the variables
    must be redeclared in the new program. They no
    longer come along with the function
  • Global variables can be affected by any function,
    leading to errors. In a program with many
    functions, finding the functions that caused an
    error can prove difficult

11
Passing Values to Functions
4
  • Many real-world functions you perform require
    that you provide information
  • A particular task might always be carried out in
    the same way, but with specific data
  • Consider a program that computes the amount of
    sales tax due on an item
  • You can write the prototype for computeTax() in
    one of two ways
  • void computeTax(int)
  • OR
  • void computeTax(int price)

12
Passing Values to Functions
4
13
Passing Values to Functions
4
  • Perform the steps on page 131 of the textbook, to
    modify the HoursAndRate program you wrote earlier
    so that results now print from within a function

14
Using Classes and Objects as Arguments to
Functions and as Return Types of Functions
4
  • A function can contain a variety of combinations
    of actions
  • Some functions contain local variables declared
    within the function body
  • Some functions return and receive nothing
  • Others return values, receive values, or both
  • Functions may receive any number of variables as
    parameters, but may return, at most, only one
    variable of one type

15
Using the Customer Class with Functions
4
16
A Program That Calls Two Functions to Get Two
Results
4
Ex4-27.cpp

17
Passing Addresses to Functions
4
  • Just as variable values may be passed to and
    returned from functions, so may variable
    addresses
  • Passing an address to a function avoids having
    the function copy the passed object, a process
    that takes time and memory
  • You also can pass addresses to a function if you
    want a function to change multiple values
  • If you pass addresses to function, however, the
    function can change the contents at those actual
    memory addresses, eliminating the need to return
    any values at all

18
Passing Addresses to Functions
4
  • As an alternative to the program shown in Figure
    4-27, you can pass two memory addresses to one
    function, making a single function call, as shown
    in Figure 4-28
  • In the program shown in Figure 4-28, four items
    are passed to the results() function the value
    of a, the value of b, the address of dividend,
    and the address of modulus
  • In turn the results() function receives four
    items
  • num1, which holds the value of a
  • num2, which holds the value of b
  • oneAddress, a pointer that holds the address of
    dividend
  • anotherAddress, a pointer that holds the address
    of modulus

19
A Program That Calls One Function to Get Two
Results
4
Ex4-28.cpp
20
Passing Addresses to Functions
4
  • Passing an address of a variable to a function
    has a number of advantages
  • If the function is intended to alter the
    variable, it alters the actual variable, not a
    copy of it
  • You can write the function to alter multiple
    values
  • When you send the address of a variable to a
    function, the function does not need to make a
    copy of the variable

21
Using Reference Variables with Functions
4
  • To create a second name for a variable in a
    program, you can generate an alias, or an
    alternate name
  • In C a variable that acts as an alias for
    another variable is called a reference variable,
    or simply a reference

22
Declaring Reference Variables
4
  • You declare a reference variable by placing a
    type and an ampersand in front of a variable
    name, as in double cash and assigning another
    variable of the same type to the reference
    variable
  • double someMoney
  • double cash someMoney
  • A reference variable refers to the same memory
    address as does a variable, and a pointer holds
    the memory address of a variable

23
Declaring Reference Variables
4
Ex4-29.cpp ex 4-30.cpp
24
Declaring Reference Variables
4
  • There are two differences between reference
    variables and pointers
  • Pointers are more flexible
  • Reference variables are easier to use
  • You assign a value to a pointer by inserting an
    ampersand in front of the name of the variable
    whose address you want to store in the pointer
  • Figure 4-30 shows that when you want to use the
    value stored in the pointer, you must use the
    asterisk to dereference the pointer, or use the
    value to which it points, instead of the address
    it holds

25
Passing Variable Addresses to Reference Variables
4
  • Reference variables are easier to use because you
    dont need any extra punctuation to output their
    values
  • You declare a reference variable by placing an
    ampersand in front of the variables name
  • You assign a value to a reference variable by
    using another variables name
  • The advantage to using reference variables lies
    in creating them in function headers

26
Comparing Pointers and References in a Function
Header
4
27
Passing Variable Addresses to Reference Variables
4
  • When you pass a variables address to a function,
    whether with a pointer or with a reference, any
    changes to the variable made by the function also
    alter the actual variable
  • In addition, the function no longer needs to make
    a copy of the variable
  • A function that receives an address may change
    the variablebut sometimes you might not want the
    variable changed

28
Using a Constant Reference
4
29
Passing Arrays to Functions
4
  • An array name actually represents a memory
    address
  • Thus, an array name is a pointer
  • The subscript used to access an element of an
    array indicates how much to add to the starting
    address to locate a value
  • When you pass an array to a function, you are
    actually passing an address
  • Any changes made to the array within the function
    also affect the original array

30
Passing an Array to a Function
4
Ex-34.cpp
31
Inline Functions
4
  • Each time you call a function in a C program,
    the computer must do the following
  • Remember where to return when the function
    eventually ends
  • Provide memory for the functions variables
  • Provide memory for any value returned by the
    function
  • Pass control to the function
  • Pass control back to the calling program
  • This extra activity constitutes the overhead, or
    cost of doing business, involved in calling a
    function

32
Using an Inline Function
4
33
Inline Functions
4
  • An inline function is a small function with no
    calling overhead
  • Overhead is avoided because program control never
    transfers to the function
  • A copy of the function statements is placed
    directly into the compiled calling program
  • The inline function appears prior to the main(),
    which calls it
  • Any inline function must precede any function
    that calls it, which eliminates the need for
    prototyping in the calling function

34
Inline Functions
4
  • When you compile a program, the code for the
    inline function is placed directly within the
    main() function
  • You should use an inline function only in the
    following situations
  • When you want to group statements together so
    that you can use a function name
  • When the number of statements is small (one or
    two lines in the body of the function)
  • When the function is called on few occasions

35
Using Default Arguments
4
  • When you dont provide enough arguments in a
    function call, you usually want the compiler to
    issue a warning message for this error
  • Sometimes it is useful to create a function that
    supplies a default value for any missing
    parameters

36
Using Default Arguments
4
  • Two rules apply to default parameters
  • If you assign a default value to any variable in
    a function prototypes parameter list, then all
    parameters to the right of that variable also
    must have default values
  • If you omit any argument when you call a function
    that has default parameters, then you also must
    leave out all arguments to the right of that
    argument

37
Examples of Legal and Illegal Use of Functions
with Default Parameters
4
Ex4-39.cpp
38
Overloading Functions
4
  • In most computer programming languages, each
    variable used in a function must have only one
    name, but C allows you to employ an alias
  • Similarly, in most computer programming
    languages, each function used in a program must
    have a unique name
  • You dont have to use three names for functions
    that perform basically the same task, C allows
    you to reuse, or overload, function names

39
Overloading Functions
4
  • Whether you use the function shown in Figure 4-40
    or 4-41, you still must write three versions of
    the functionone for each type of argument you
    want to support
  • When you overload a function, you must ensure
    that the compiler can tell which function to
    call
  • When the compiler cannot tell which version of a
    function to use, you have created ambiguity

40
Three Overloaded Functions That Perform Similar
Tasks
4
Ex4-41.cpp
41
A Simple Recursion Function
  • include
  • int Fac(int n)
  • if (n 1)
  • return Fac(n-1) n
  • else
  • return 1
  • void main()
  • int i
  • cout
  • cin i
  • cout"

42
Summary
4
  • Functions are programming modules
  • You can define a function by writing it above the
    function that uses it, or by including the
    functions filename at the top of the file that
    uses it
  • When you write functions, you employ procedural
    abstractionthe process of extracting the
    relevant attributes of an object
  • Global variables are known to every function and
    block in a program

43
Summary
4
  • Local variables are accessible or in scope only
    within the block where they are defined
  • The header of a function consists of the return
    type, the name, and the argument list
  • A function can return a value that the calling
    function can use
  • You can pass an argument or parameter to a
    function
  • You can pass class objects to functions and
    return them from functions in the same way you
    work with scalar variables

44
Summary
4
  • Passing an address to a function allows you to
    avoid having the function copy the passed object
    and allows a function to change multiple values
    without returning them
  • In C a variable that acts as an alias for
    another variable is called a reference variable
  • Because an array name is a memory address, when
    you pass an array name to a function, you are
    actually passing an address

45
Summary
4
  • An inline function is a small function with no
    overhead
  • You should use inline functions when the number
    of statements is small and when the function is
    called infrequently
  • Default parameters provide values for any
    parameters that are missing in the function call
  • C allows you to reuse, or overload, function
    names
  • To prevent ambiguity, overloaded functions must
    have argument lists of different types
Write a Comment
User Comments (0)
About PowerShow.com