Chapter 3 Programming 2
Chapter 3 Programming 2
FUNCTION
3. What is a function?
One of the best ways to tackle a problem is to start with the overall goal, then dividethis goal
into several smaller tasks. You should never lose sight of the overall goal,but think also of
how individual pieces can fit together to accomplish such a goal.If your program does a lot,
break it into several functions. Eachfunction should do onlyone primary task.
iii. they can consist of letters, numbers, and the underscore (_) character.
3. All function names have one set of parenthesis immediatelyfollowing them. This
helps you (and C++ compiler)differentiate them from variables.
The interface of a function (also called its prototype) specifies howit may be used. It consists
of three entities:
The function return type. This specifies the type of value the function returns. A
function which returns nothing should have a return type void.
Thefunctionparameters(alsocalleditssignature).Thisisasetofzeroormoretypedi
dentifiersusedforpassingvaluestoandfromthefunction.
A function definition consists of two parts: interface (prototype) &body. The brace of a
function contains the computational steps (statements) that computerize the function. The
definition consists of a line called the decelerator.
Calling a function means making the instruction of the function tobe executed.
A function call consists of the function name followed by the call operator brackets ‘()’,
inside which zero or more comma-separated arguments appear. The number and type of
arguments should match the number of function parameters.
When a function call is executed, the arguments are first evaluated and their resulting
values are assigned to the corresponding parameters.The function body is then executed.
Finally the return value (if any) is passed to the caller.
Given the next program, which function is the calling function andwhich is the called
function?
#include<iostream.h> nextMsg();
#include<conio.h> return 0;
3. 4. Function Parameters and arguments
void nextMsg(); }
The parameters of a function are list of variables used by the function to perform its task and
void nextMsg()
the argumentsintpassed
main()to the function during calling of a function are values sent to the
function.The {arguments of function calling can be using either of the
{ two supported styles in
C++: passing by value or passing by reference.
cout<< “GoodBye!\n”;
3.4.1. Passing by value:
A value parameter receives a copy of only the value of the argumentpassed to it. As a result,
if the function makes any changes to the parameters, this will not affect the argument. For
instance:
The single parameter of Foo is a value parameter. As far as thisfunction is concerned, num
behaves just like a local variable insidefunction. When thefunction is called and x passed to it,
numreceives a copy of the value of x. As a result, although num is set to0 by the function, this
does not affect x. the program produces thefollowing output:
Num = 0
x = 10
Passing arguments in this way, where the function creates copies ofthe arguments passed to it
is called passing by value.
3.4.2.PassingbyReference:
A reference parameter, on the other hand, receives the argument passed to it and workson
it directly. Any change made by the function to a reference parameter is in effect directly
applied to the argument.
#.....
num = 0;
int main(void)
int x = 10;
Foo(x);
getch();
return 0;
}
The parameter of Foo is a reference parameter. Num will correspond to x for this specific
program as it x is sent by its reference and not its value. Any change made on num will
be effected to x. Thus, the program produces the following output:
num = 0
x=0
Everything defined at the program scope level (outside functions) is said to have a global
scope, meaning that the entire program knows each variable and has the capability to change
any of them.Eg.
int main(void)
//…
Global variables are visible (“known”) from their point of definitiondown to the end of the
program.Each block in a program defines a local scope. Thus the body of a function
represents a local scope. The parameters of a function have the same scope as the function
body.Variables defined within a local scope are visible to that scope only. Hence, a variable
need only be unique within its own scope. Local scopes may be nested, in which case the
inner scope overrides the outer scopes. Eg:
if(xyz > 0) {
…}}
3.6. Scope Operator
Because a local scope overrides the global scope, having a local variable with the same name
as a global variable makes the latter inaccessible to the local scope.Eg
int num1;
//…
The global num1 is inaccessible inside fun1(), because it is overriddenby the local num1
parameter.This problem is overcome using the scope operator ‘::’ which takes aglobal entity
as argument.
int num1 = 2;
//…
num1=33;
//…
The terms automatic and static describe what happens to local variables when a function
returns to the calling procedure. By default, all local variables are automatic, meaning that
they are erased when their function ends. You can designate a variable as automatic by
prefixing its definition with the term auto.Eg. The two statements after main()’s opening
brace declaredautomatic local variables:
main()
int i;
auto float x;
The opposite of an automatic is a static variable. All global variables are static and, as
mentioned, all static variables retain their values. Therefore, if a local variable is static, it too
retains its value when its function ends-in case this function is called a second time.To declare
a variable as static, place the static keyword in front of the variable when you define it.
Static variables can be declared and initialized within the function, butthe initialization will be
executed only once during the first call.If static variables are not declared explicitly, they will
be declared to 0automatically.Eg.
voidmy_fun()
{
staticintnum;
staticintcount=2;
count=count*5;
num=num+4;
}
In the above example:
During the first call of the function my_fun(), the static variable count will be initialized
to 2 and will be multiplied by 5 at line three to have the value 10. During the second call
of the same function count will have 10 and will be multiplied by 5.
During the first call of the function my_fun(), the static variable num will be initialized
to 0 (as it is not explicitly initialized) and 4 will be added to it at line four to have the
value 4. During the second call of the same function num will have 4 and 4 will be add to
it again.
N.B. if local variables are static, their values remain in case the function is called again.
3.8. Inline functions
Suppose that a program frequently requires finding the absolute value of an integer
quantity. For a value denoted by n, this may be expressed as:(n > 0 ? n : -n)
int Abs(int n)
It is reusable.
{
Returnn>0?n:-n;
}
The effect of this is that when Abs is called, the compiler, instead of generating code to
call Abs, expands the program body and substitutes the body of Abs in place of the call.
While essentially the same computation is performed, no function call is involved and
hence nostack frame is allocated.
Another good reason to inline is that you can sometimes speed up your program by
inlining the right function. Instead of calling the function every time it is invoked, the
compiler will replace the function call with a copy of the function body. If it's a small
function which gets called a lot, this can sometimes speed things up.
Most of the advantage of inline functions comes from avoiding the overhead of calling
an actual function. Such overhead includes saving registers, setting up stack frames, and
so on. But with large functions the overhead becomes less important.
4.9.Defaultargumentsandfunctionoverloading
C++ has two capabilities thatregular C doesn’t have. Default arguments and function
overloading.
Eg. You might pass a function an error message that is stored in a character array, and the
function displays the error for a certain period of time. The prototype for such a function can
be this:
Therefore, to request that pr_msg() display the line ‘Turn printeron’, you call it this way:
As you write more of the program, you begin to realize that you are displaying one message-
for instance, the ‘Turn printer on’ msg- more often than any other message.Instead of calling
the function over and over, typing the same message each time, you can set up the prototype
for pr_msg() so that it defaults to the ‘turn printer on’ message in this way:
This makes your programming job easier. Because you would usually want pr_msg() to
display ‘turn printer on’, the default argument list takes care of the message and you don’t
have to pass the message when you call the function.
For functions having more than one argument with default, the parameters with possible
default value should be declared in the right side of the function definition and prototype.
3.9.2.Overloaded Functions
Unlike C, C++ lets you have more than one function with the same name. In other words,
you can have three functions called abs() in the same program.
Functions with the same name are called overloaded functions. C++ requires that each
overloaded functions differ in its argument list. Overloaded functions enable you to have
similar functions that work on different types of data.
Suppose that you wrote a function that returned the absolute valueof what ever number
you passed to it:
3.10. Recursion
- factorial of 0 is 1
The second line clearly indicates that factorial is defined in terms ofitself and hence can be
expressed as a recursive function.
return n = = 0 ? 1 : n * factrial(n-1);
}
For n set to 4, the following figure shows the recursive call:
The stack frames for these calls appear sequentially on the runtimestack, one after the other.
A recursive function must have at least one termination condition which can be
satisfied.Otherwise, the function will call itselfindefinitely until the runtime stack
overflows.