You are on page 1of 31

FUNCTIONS

1
Functions
• A function is a block of instructions that is
executed when it is called from some other
point of the program.
• Advantages
– Reusability
– Data Abstraction
– Modularity

2
Predefined Functions
Libraries

• C++ comes with libraries of predefined


functions.
• How do we use predefined (or library)
functions?
• Everything must be declared before it is used.
The statement #include <file> brings the
declarations of library functions into your
program, so you can use the library functions.

3
Predefined Functions
Libraries

#include <cmath.h> // include declarations of math


// library functions
#include <stdio.h> // include definitions of
// stdio.h objects
int main()
{
printf(“ %d\n”, sqrt(3.0)) // call math library function
} // sqrt with argument 3.0, send
// the returned value to cout
4
Function call

• A function call is an expression consisting of a function


name followed by arguments enclosed in parentheses.
Multiple arguments are separated by commas.
• Syntax:
FunctionName(Arg_List)
where Arg_List is a comma separated list of arguments.
• Examples:
– side = sqrt(area);
– printf(“2.5 to the power 3.0 is %d“, pow(2.5, 3.0));

5
A Function call
//Computes the size of a dog house that can be purchased
//given the user’s budget.
#include <stdio.h>
#include <math.h>
int main( )
{
const double COST_PER_SQ_FT = 10.50;
double budget, area, length_side;
printf( "Enter the amount budgeted for your dog house $“);
scanf( “%f”, &budget);
area = budget/COST_PER_SQ_FT;
length_side = sqrt(area); // the function call

6
A Function call

printf( "For a price of $ %d \n" , budget);


printf( "I can build you a luxurious square dog house\n“);
printf( "that is %d " ,length_side);
printf( " feet on each side.\n“);

return 0;
}

7
Programmer Defined Functions
function prototypes
• A function prototype tells you all the information you need to
call the function. A prototype of a function (or its definition)
must appear in your code prior to any call to the function.
• Syntax: Don’t forget the semicolon
– Type_of_returned_value Function_Name(Parameter_list);
– Place prototype comment here.
– Parameter_list is a comma separated list of parameter
definitions:
type_1 param_1, type_2 param_2, …. type_N param_N
• Example:
double total_weight(int number, double weight_of_one);
// Returns total weight of number of items that
// each weigh weight_of_one
8
Programmer Defined Functions

#include <stdio.h>
double total_cost(int number_par, double price_par);
//Computes the total cost, including 5% sales tax,
//on number_par items at a cost of price_par each.
int main( )
{
double price, bill;
int number;
printf( "Enter the number of items purchased: “);
scanf( “%d”, &number);
printf( "Enter the price per item $“);
scanf(“%d”, &price);
bill = total_cost(number, price); The function call
printf(“%d items at $ %d each.\n“, number, price);
printf( "Final bill, including tax, is $%d\n“, bill);
9
return 0;
3.3 Programmer Defined Functions
Display 3.3 A function Definition (Slide 2 of 2)

double total_cost(int number_par, double price_par) The function


{ heading
heading
const double TAX_RATE = 0.05; //5% sales tax The function
double subtotal; The function definition
body
subtotal = price_par * number_par;
return (subtotal + subtotal*TAX_RATE);
}

10
Programmer Defined Functions
Call-by-value Parameters
Consider the function call:
bill = total_cost(number, price);

• The values of the arguments number and price are “plugged” in


for the formal parameters . This process is (A precise definition
of what “plugged” means will be presented later. For now, we
will use this simile.)
• A function of the kind discussed in this chapter does not send
any output to the screen, but does send a kind of “output” back
to the program. The function returns a return-statement instead
of cout-statement for “output.”

11
Programmer Defined Functions
Alternate form for Function Prototypes
• The parameter names are not required:
double total_cost(int number, double price);

• It is permissible to write:
double total_cost(int, double );

• Nevertheless, code should be readable to programmers as well


as understandable by the compiler, so check for readability and
chose to use parameter names when it increases readability.

12
PITFALL
Arguments in the wrong order
• When a function is called, C++ substitutes the first argument
given in the call for the first parameter in the definition, the
second argument for the second parameter, and so on.
• There is no check for reasonableness. The only things checked
are: i) that there is agreement of argument type with parameter
type and ii) that the number of arguments agrees with the
number of parameters.
• If you do not put correct arguments in call in the correct order,
C++ will happily assign the “wrong” arguments to the “right”
parameters.

13
Programmer Defined Functions
Summary of Syntax for a Function that Returns a Value.
Function Prototype:
Type_Returned Function_Name(Parameter_List);
Prototype Comment
function header
Function Definitions
Type_Returned Function_Name(Parameter_List)
{
Declaration_1
Declaration_2
... Must include one or
Declaration_Last; more return statements.
body Executable_1;
Executable_2;
...
Executable_Last
}

14
Functions with no return value
General format
void function_name ([parameters])
{
<function_body>
}
Declaring Void Functions
• Similar to functions returning a value
• Return type specified as "void"
• Example:
– Function declaration/prototype:
void showResults( double fDegrees,
double cDegrees);
• Return-type is "void"
• Nothing is returned
Declaring Void Functions
• Function definition:
void showResults(double fDegrees,
double cDegrees)
{
statements;
statements;
}
• Notice: no return statement
Calling Void Functions
• Same as calling predefined void functions
• From some other function, like main():
– showResults(degreesF, degreesC);
– showResults(32.5, 0.3);
• Notice no assignment, since no
value returned
• Actual arguments (degreesF, degreesC)
– Passed to function
– Function is called to "do it’s job" with the
data passed in
Returning more than one value

#include <stdio.h>
void prevnext (int x, int &prev, int &next)
{ prev = x-1;
next = x + 1;}
int main {int x = 100,y,z;
prevnext(x,y,z);
printf(”previous %d next %d”,y, z);
return 0;} 20
Default Values in arguments
#include<stdio.h>
int divide(int a, int b=2) {
int r; r=a/b; return(r);}
int main(){
printf(“%d\n”,divide(2));
printf((“%d\n”, divide(20,4));
return 0; }

21
Overloading Function Names
• C++ distinguishes two functions by examining the
function name and the argument list for number
and type of arguments.
• The function that is chosen is the function with
the same number of parameters as the number of
arguments and and that matches the types of the
parameter list sufficiently well.
• This means you do not have to generate names for
functions that have very much the same task, but
have different types.

22
Overloading Function Names

//Illustrates overloading the function name ave.


#include <stdio.h>
double ave(double n1, double n2);
//Returns the average of the two numbers n1 and n2.
double ave(double n1, double n2, double n3);
//Returns the average of the three numbers n1, n2, and n3.
int main( )
{
using namespace std;
printf( "The average of 2.0, 2.5, and 3.0 is %f \n“, ave(2.0, 2.5,
3.0));
printf( "The average of 4.5 and 5.5 is %f\n“, ave(4.5, 5.5));
return 0;
}
23
Overloading Function Names

double ave(double n1, double n2) Both these functions have the
{ same name, but have
parameter
return ((n1 + n2)/2.0); lists that are have different
} numbers of parameters.

double ave(double n1, double n2, double n3)


{
return ((n1 + n2 + n3)/3.0);
}

24
Overloading Function Names
Automatic Type Conversion

• We pointed out that when overloading function names, the C++


compiler compares the number and sequence of types of the
arguments to the number and sequence of types for candidate
functions.
• In choosing which of several candidates for use when overloading
function names, the compiler will choose an exact match if one if
available.
• An integral type will be promoted to a larger integral type if
necessary to find a match. An integral type will be promoted to a
floating point type if necessary to get a match.

25
Overloading Function Names

//Determines whether a round pizza or a rectangular pizza is the best buy.


#include <stdio.h>
double unitprice(int diameter, double price);
//Returns the price per square inch of a round pizza.
//The formal parameter named diameter is the diameter of the pizza
//in inches. The formal parameter named price is the price of the pizza.
double unitprice(int length, int width, double price);
//Returns the price per square inch of a rectangular pizza
//with dimensions length by width inches.
//The formal parameter price is the price of the pizza.
int main( )
{
int diameter, length, width;
double price_round, unit_price_round,
26
price_rectangular, unitprice_rectangular;
Overloading Function Names

printf( "Welcome to the Pizza Consumers Union.\n“);


printf( "Enter the diameter in inches of a round pizza: “);
scanf(“%d”, &diameter);
printf( "Enter the price of a round pizza: $“);
scanf(“%d”, &price_round);
printf( "Enter length and width in inches \n of a rectangular
pizza: “);
scanf(“%d %d”, & length, &width);
printf( "Enter the price of a rectangular pizza: $“);
scanf(“%f”, & price_rectangular);

unitprice_rectangular = unitprice(length, width,


price_rectangular);
27
unit_price_round = unitprice(diameter, price_round);
Overloading Function Names

printf( "Round pizza: Diameter = %d inches\n”, diameter);


printf( "Price = $ %d" ,price_round);
printf( " Per square inch = $%f \n“, price_round);
printf( "Rectangular pizza: length = %d inches\n" , length );
printf( "Rectangular pizza: Width = %d inches\n" , widht );
printf( "Price = $ %d“, price_rectangular);
printf( " Per square inch = $ %d \n" ,unitprice_rectangular);
if (unit_price_round < unitprice_rectangular)
printf( "The round one is the better buy.\n“);
else
printf( "The rectangular one is the better buy.\n“);
printf( "Buon Appetito!\n“);

return 0;
}
28
Function Template
• Is a single, complete function that serves as
a model for a family of functions
• Generic, flexible
• Data type of the arguments of the function
follow the data type of the actual value that
is passed unto it.

29
Function Template
#include <stdio.h>
template<class T>
void showabs(T number)
{if (number<0)
number = -number;
printf("the absolute value of the number is"
<<number<<endl;}
int main ()
{ int num1 = -4;
float num2 = -4.23;
double num3= -4.23456;
showabs(num1);
showabs(num2);
showabs(num3); return 0; }

30
Reference
• Slides by David B Teague, Western
Carolina University,

You might also like