Вы находитесь на странице: 1из 19

MODULE IV

Programmer-Defined Functions
Module Contents
chapter 6 in Text Book
● Basics (chapter 6)
● A Tasty Problem – computing volume of a donut
● Some Useful Functions – max, min, isvowel, factorial
● Integrating a Quadratic Polynomial – computing value of a nxn + an-1 xn-1 + …. + a1x + a0
● The Logic Scope
● Displaying a Price Interval Chart – an example program
● Recursive Functions
● Advanced Parameter Passing (chapter 7)
– Reference Parameters, Passing Objects by Reference
● Validating Telephone Access Codes – an example
● Constant Parameters and Default Parameters
● Casting of Function Parameters
● Function Overloading
● Random Numbers
● A Factory Automation Trainer
Function Basics
● Function is a block of code to perform a particular
task in a problem solution
● Functions aid in modular programming
– Increase readability of program
– Functional abstraction of a task
● A function has an interface and definition
– In software libraries, interfaces of functions are in header
file
– Definition of functions is in object file
Function Interface
● Also called function prototype
● Syntax - ReturnType functionName(/*parameter list*/);
● ReturnType is the type of value that the function returns; if a function does not
return any value, then return type is void
● FunctionName is an identifier
– Must follow naming rules of C++
– Should be meaningful as to what it does
● Parameter list is the inputs that function needs in order to perform its task
– Each parameter has the syntax: dataType identifier
– Multiple parameters are separated by comma
– Each parameter is a variable declaration within the function
– Parameters in function prototype(and definition) are called formal parameters
– Parameters are created and initialized with actual parameter when the function is invoked
Function Prototype
● In C++, functions are declared first and defined later
elsewhere
– Except for inline functions
● Function declaration is called function prototyping
● Function declaration specifies its interface
– How other functions can use it
● Function prototype is sufficient to compile the program that
has its usage
● However, function definition is required to execute the
program
Function Definition
● Function definition includes both
– Complete interface of the function
– Statements that perform its task
● Syntax:
return_type function_name(/*parameters*/)
{
//statements to perform the task
//return statement, if not void
}
Function Invocation
● Function invocation supplies the parameters to the function
● When a function is invoked
– Flow of program execution leaves the calling function
● All data pertaining to calling-function is pushed to stack
– Enter the code of called function
● Function activation record is created
● Formal parameter identifiers are allocated memory
● Initialized by the respective values of actual parameters
● Executes the code in function definition
● Returns value
– Flow of program resumes in calling-function
Scope of Variables
● scope of a variable is defined as the extent of the program
code within which the variable can we accessed or
declared or worked with
● C++ variables can have one of the two scopes
– Local scope - Variables defined within a function or block
● Anything between ‘{‘ and ‘}’ is said to inside a block
● Local variables do not exist outside the block in which they are declared
– Global scope - Variables declared at the top of the program
outside all of the functions or blocks.
● They are available through out the life time of a program.
● They can be accessed from any part of the program
Local Scope
● Since control structures are defined in blocks, variables
declared in them are local to them
● Variables declared in data structures – struct and class – are
local to these structures
– They are available only within the structure
● We can control their access
● Variables declared in functions are local to functions
● If a local variable with the same name as that of global variable
inside a function exists,
– The value of the local variable has precedence within function
– If we need to access global variable, we must resolve its scope
Inline Functions
● Function call involves
– Load function in memory
– Create activation record
– stacking calling function’s data,
– jump to function code,
– Copy argument values, execute code
– retrieve calling function’s data
– and jump back to calling function
● When function code is short, the above task may take more time than executing its
code
● C’s macros provide faster execution in such cases
– Unsafe. Not recommended in C++
● C++ provides inline functions to replace such macros
– An inline-function's code replaces the function call
Inline Functon's Pros and Cons
● Pros:
– It speeds up program execution by avoiding function calling overhead
– It save overhead of variables push/pop on the stack, when function
calling happens
– It save overhead of return call from a function
– It increases locality of reference by utilizing instruction cache
– By marking it as inline, you can put a function definition in a header file
● Cons
– Increases executable program size on the disk
– If we change function code, we need to recompile the program
Inline Functions
● Syntax:
– inline ret-type fn-name(/*parameters*/)
{//function body}
● Function declaration and definition must be together
● While compiling, compiler replaces function call with its body
● Inline is a request to compiler
– To optimize code for faster execution
● Compiler may override this request when function body
– is large
– has loops
– Has static variables
– If function is recursive
Recursive Functions
● Recursion is a method of solving problems that involves breaking
a problem down into smaller and smaller subproblems until you
get to a small enough problem that it can be solved trivially
● A function that calls itself is known as recursive function
● The process of calling itself is called recursion

Recursive function has
– a base condition

Provides trivial solution
– And a recursive condition

Breaks down the task into smaller version of itself

Example in int_to_binary function
Parameter Passing to Function
● Call by value
● Call by reference
– Using pointer
– Using reference
void swap(int a, int b) void swap(int *a, int *b) void swap(int &a, int &b)
{ { {
int temp = a; int temp = &a; int temp = a;
*a = &b; a = b;
a = b;
*b = temp; b = temp;
b = temp;
} }
}
Constant Parameters
● Objects and arrays are generally passed by
reference
● Function has access to modify these objects
● When we do not want the function to modify the
object parameters, we declare the as const
● Function can not modify const parameters
Default Parameters
● C++ allows default values for function parameters
– Default arguments are only allowed in the parameter lists of function
declarations
– not allowed in the declarations of pointers to functions, references to
functions, or in typedef declarations
● Only tail-end parameters can have default value
● Allows a function to be called without providing one or more
trailing arguments
● Default argument for a given parameter has to be specified no
more than once
– Therefore, default value must be in the function prototype
Function Overloading
● To specify more than one definition for a function
name or an operator in the same scope
● Overloaded functions will have the same name but
differ in
– Types of arguments
– Number of arguments
– Order of arguments
● May differ in return type
– But that alone is not sufficient
Function Overloading
Examples
1.String nameInIntials(string);
String nameInIntials(char *);
2.Int numberToWords(int);
Float numberToWords(float);
3. String rupees_paise_to_words(int, int);
4. String rupees_paise_to_words(float);
String rupees_paise_to_words(int);
Operator Overloading
● Operators in C++ are defined as functions
● We can overload all most all operators to
extend their meaning to user-defined types
● Ex: string class overloaded operators
– = += == > >= < <= >> <<
● Ex: we will discuss in class

Вам также может понравиться