Functions in C++ Programming Lectures
Functions in C++ Programming Lectures
LECTURE # 6: FUNCTIONS - A
BSE 1
Joddat Fatima
1
joddat.fatima@gmail.com
Department of C&SE
Bahria University Islamabad
INTRODUCTION
Divide and conquer
Constructa program from smaller pieces or components
Each piece more manageable than the original program
Functions
Modularize a program
Software reusability
Call function multiple times
Local variables
Known only in the function in which they are defined
All variables declared in function definitions are local
variables
Parameters
Local variables passed to function when called
Provide outside information
3
PREDEFINED FUNCTION
5
FUNCTION CALLS
6
FUNCTION LIBRARY
Function prototype
Tells compiler argument type and return type of function
int square( int );
Function takes an int and returns an int
Explained in more detail later
Calling/invoking a function
square(x);
Parentheses an operator used to call function
Pass argument x
Function gets its own copy of arguments
10
FUNCTION DEFINITION
Return-value-type
Data type of result returned (use void if nothing returned)
11
FUNCTION PROTOTYPING
Function signature
Part of prototype with name and parameters
double maximum( double, double, double );
Argument Coercion
Force arguments to be of proper type
Converting int (4) to double (4.0)
cout << sqrt(4)
Conversion rules
Arguments usually converted automatically
Changing from double to int can truncate data
3.4 to 3
13
14
SCOPE RULE
Block scope
Begins at declaration, ends at right brace {
Can only be referenced in this range
Global Variables
Local
variables, function parameters
static variables still have block scope
Storage class separate from scope
Function-prototype scope
Parameterlist of prototype
Names in prototype optional
Compiler ignores
In a single prototype, name can be used once 15
LOCAL VARIABLES
16
GLOBAL CONSTANT
Example:
const double PI = 3.14159;
double volume(double);
int main()
{….}
17
PI is available to the main function and to function volume
GLOBAL VARIABLES
18
EXAMPLE FUNCTION
19
EXAMPLE # 1
#include <iostream>
1 4 9 16 25 36 49 64 81 100
int square( int y )
{
return y * y;
}
20
EXAMPLE # 2
#include <iostream>
double maximum( double, double, double );
int main()
{
double number1, number2,number3;
cout << "Enter three floating-point numbers: ";
cin >> number1 >> number2 >> number3;
cout << "Maximum is: "<< maximum( number1, number2, number3 ) << endl;
return 0;
}
22
23