Sei sulla pagina 1di 44

Chapter 11

Functions

Introduction

Large programs are generally avoided because it is difficult to manage. Thus, they are broken into smaller units known as function. A function is a subprogram that acts on data and often returns a value. Functions in program makes program easy, reduce program size, makes program more readable etc.

Function Statistics

Programmers write program that consist of many small functions. A program written with many functions is easier to maintain, update and debug. Ideally, main() function should be short and should consist primarily of function calls. Each function has its own name. Functions are building blocks of C++.

Types of Functions

C++ broadly defined two types of functions:

1) Built in (or library) functions. 2) User defined functions.

Built in Functions

These functions are part of the compiler package.

These are part of standard library made available by the compiler.


For example, exit( ), pow( ), sqrt( ), strlen( ).

User defined Functions

The user-defined functions are created by user, i.e., the programmer. These functions are created as per requirements of your program.

Function Definition

In C++, a function must be defined before it is used anywhere in the program. The general form of function definition is: type function_name(parameter list) { body of the function }

Description

Type: specifies the type of value that the return statement of the function returns. No type is specified, the compiler assumes that the function returns an integer value. The parameter list is a comma-separated list of variables of a function referred to as its arguments. A function may be without any parameters. A function definition must have a return statement.

Function Prototype

A function prototype is declaration of the function that tells the program about the type of the value returned by the function and the number and type of arguments. A declaration introduces a (function) name to the program. The prototype declaration looks like a function definition except that it has no body. Example int gcd(int no1, int no2);

Function definition

A definition is a declaration that also tells the program what the function is doing and how it is doing. A definition is automatically also a declaration. Function Prototype has three parts:
ii) name of function iii) argument list.

i) return type

int

add

(int no1, int no2)

Need for Prototypes

Function prototype enables a compiler to carefully compare each use of the function with the prototype to determine whether the function is invoked properly. Any wrong number or type of arguments are reported. Thus it makes program easy as C++ can straightly point to the error. C++ makes the function prototype essential.

Arguments

In a function declaration, the name of the arguments are optional. float volume(int a, int b, int c); float area (float, float);

A function declaration can skip the argument names but a function definition can not.

Use of Void

Void data types specifies an empty set of values and it is used as the return type for functions that do not return a value. A function that do not return a value is declared as follows: void function_name(parameter_list); Void function cannot be used in an assignment statement. A function that does not require any parameter can be declared as follows: type function_name(void);

Accessing a function

A function is called (or invoked, or executed) by providing the function name, followed by the parameters being sent enclosed in parenthesis. Function which looks like: float area(float, float); The function call statement may look like: area (a, b) //where a & b have to be float type

Check your progress

WAP to create function add for int data types. WAP to create function cube for float type. WAP to use function in a program without any argument.

Default Arguments

C++ allows to assign default values to a functions parameter(s) which is useful in case a matching argument is not passed in the function call statement. The default values are specified at the time of function declaration.
float interest (float pri, int time, float rate=0.10); float interest (float pri=2000, int time =2, float rate = 0.10);

Constant Arguments

By passing constant arguments, means that function can not modify these arguments. In order to make an argument constant to a function, we can use the keyword const as shown below: int sum (const int a, const int b); The qualifier const in function prototype tells the compiler that the function should not modify the argument.

Possible function styles

Style 1: void function with NO arguments. void <function name> ( ) void <function name> (void) Style 2: void function with some arguments. void <function name>(<argument list>) Style 3: Non-void function with No arguments. <return type> <function name> ( ) Style 4: Non-void function with some arguments. <return type> <function name> (<argu list>)

Check your progress

WAP to write function for finding simple interest. WAP to show a use of void function with no arguments. WAP to show a use of void function with some arguments.

Call by Value

The function invoked by call by value method copies the values of actual parameters into the formal parameters, that is, the function creates its own copy of argument values and then uses them. In call by value method, the changes are not reflected back to the original values. Example CH11_6 During call by value, any change in the formal parameter is not reflected back to actual parameter.

Actual & Formal parameters

The parameters that appear in a function call statement are actual parameters. int change(int); int ori=10; The parameters that appear in function definition are formal parameters. int change(int a) { a =20; return a; }

Calling Function with Arrays

Array argument passed in a function is treated like a pointer (Memory address) by C++. It interprets an array name as the address of its first element. When an array is used as an argument to a function, only the address of the array gets passed, not a copy of the entire array.

Call by Reference

The call by reference method uses a different mechanism. In place of passing a value to the function being called, a reference to the original variable is passed. Reference is different name for a predefined variable. The function call statement remains the same for call by reference also. & is used to call value by reference.

Check your Progress

WAP to show function calling by call by value. WAP to swap two variables using call by reference. WAP to convert distance in feet or inches using a call by reference method.

Calling Functions with Arrays

When array is passed to a function, C++ treats the name of an array as if it were a pointer (memory address of some element). C++ interprets an array name as the address of its first element. First way: The receiving parameter of the array may itself be declared as an array. Second way: The receiving parameter may be declared as an unsized array. Third way: The receiving parameter can be declared as a pointer.

Why Returning from a Function?

It terminates the functions execution. Also passes the control back to the calling function. A function terminates when either a return statement is encountered or the last statement in the function is executed. Generally, return statement is used to terminate a function whether or not it returns a value.

The return statement

1.
2.

The return statement is used in two ways:


An immediate exit Return a value to the calling code.

Return statement in a function is not necessary, still functions rely on the return statement to stop execution either because a value must be returned or to make a functions code simpler and more efficient.

What can a function return?

Returning Values Returning Non Integer Values Returning (by) Reference

Returning values

All functions except type void, return a value. A function can return only a single value.

In a function, a return statement is missing, then the return value of the function is technically undefined.
Void functions do not return a value and hence cannot be used in expressions.

Types of functions
1.

2.

3.

Computational Functions: The functions that calculate or compute some value and return the compound value. Ex: sqrt( ) & cos( ). Manipulative Functions: The functions that manipulate information and return a success or a failure code. Procedural Functions: The functions that perform an action and have no explicit return value. Ex: exit( )

Returning Non-Integer Values

When type is not defined C++ assumes it to be int type. For the functions returning values of different data types, explicit type specifier must be given.

Returning (by) Reference

A function may also return a reference float &min (float a, float b){ if (a<b) return a; else return b; The above function returns reference to a or b rather than returning values. A function returning a reference can appear on the left-hand side of an assignment statement.

Scope Rules

The scope rules of a language are the rules that decide, in which part(s) of the program a particular piece of code or data item would be known and can be accessed therein. The program part(s) in which a particular piece of code or a data value (variable) can be accessed is known as the piece-of-code or variables scope.

Kinds of Scope

Local Scope: A name declared in a block{ } is local to that block and can be used only in it and other blocks contained in it. Function Scope: The variables declared in the outermost block of a function have function scope i.e. they can be only accessed in the function. File Scope: A name declared outside all blocks and functions has file scope. Class Scope: A name of class member has class scope and is local to its class.

Function Scope Determination


The scope for a function or a variable is determined by its place of declaration. Local Prototype: If inside a function A( ), another function B( ) is declared, function B( ) can be accessed from function A( ) only, such function declaration are local prototype. Global Prototype: If function B( ) is declared outside all the functions, then the function B( ) can be accessed from any of the functions in the file.

Global Variable

If a variable is declared outside all the function, it is said to be global variable. A GV is available to all the functions and blocks defined in the file. A GV comes into existence when the program execution starts and is destroyed when the program terminates. GV holds their values throughout the program execution. The scope of GV is file scope.

Local Variable

The LV are the ones that are defined within a function. A LV comes into existence when the function is entered and is destroyed upon exit. A LV cannot hold its value between function calls. It is defined and initialized every time a function call occurs. The only exception to this rule is static local variable.

Storage Class Specifiers

By default C++ handles a particular variable or a function in a specific manner. But this default manner of handling a variable or a function can be altered b providing a storage class specifier to a variable or a function. The storage class specifiers tell the compiler how to store the subsequent variables. storage-specifier type var_name;

Types of Storage class specifiers


Variable 1. auto 2. register 3. static 4. extern
1. 2.

Function static extern

auto

Be default, the variables defined within a function are automatic auto. An Automatic variable is not created until the function, in which it is defined, is called. It is automatically called when function is called and automatically destroyed when function is terminated. The lifetime of the variable is the time during which its parent function (that defines it) is running. The scope of an auto variable is the function scope.

register

A register declaration has characteristics of an auto variable.

all

the

Register variables provide fast access as they are stored inside CPU registers rather than in memory.

The register as well as auto can be applied only to local variables.

extern

The extern specifier is only for global variables and it can occur even in the same file that has the original variable declaration, but it is not necessary. An extern variable is initialized by the program when the file is first loaded. The lifetime or external variables is the life of the program. The scope of the external variables is the file scope.

static

There can be static global variables as well as static local variables. The static variables are permanent within their own function (in case of local variable) or file (in case of global variable). The static local variable is not destroyed when the function terminates, rather it holds its value even after functions termination but it cab be only accessed within its own function.

Storage Class Specifiers and Functions

Two of the storage class specifiers: static and extern can be used for functions. By default, the functions have program life time. static: If the keyword static appears before any function declaration, it means that the function will now have a file scope. It can be used in that file only. extern: An extern function is similar to an extern variable. The keyword extern before a function prototype indicates that this function has been defined in another file.

Potrebbero piacerti anche