Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 7

Object Oriented Programming

Lecture (1)

Functions :
Functions are the building blocks of C and C++ and the place where all program activity
occurs. This lecture examines their C-like features, including passing arguments, returning
values, returning pointer and recursion.

The General Form of a Function


The general form of a function is
ret-type function-name(parameter list)
{
body of the function
}

The ret-type specifies the type of data that the function returns. A function may return any
type of data except an array. The parameter list is a comma-separated list of variable names
and their associated types that receive the values of the arguments when the function is called.
A function may be without parameters, in which case the parameter list is empty. However,
even if there are no parameters, the parentheses are still required.

Library and User Defined Function :


In C program, functions of two type.
1- Predefined functions or library functions.
2- User defined functions.
The predefined or library functions are pre written, and place in libraries. They come along
with compiler.
User defined functions are written by the user, and the user has the freedom to choice the
name, arguments(number and type) and return data type of the function.
One of the greatest features of C is that there is no conceptual difference between the User
define functions and library functions. A user can write functions, collect them and put them
into a library, which can be used by anyone.

Function Arguments :
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. They behave
like other local variables inside the function and are created upon entry into the function and

1
Object Oriented Programming
Lecture (1)

destroyed upon exit. As shown in the following function, the parameter declarations occur
after the function name:

void sum(int a,int b)


{
int result=a+b;
printf(“%d”,result);
}

int main()
{
int x,y;
scanf(“%d%d”,&x,&y);
sum(x,y);
return 0;
}

Call by Value, Call by Reference :


In a computer language, there are two ways that arguments can be passed to functions.
The first is known as call by value. This method copies the value of an argument into the
formal parameter of the function. In this case, changes made to the parameter have no effect
on the argument.
Call by reference is the second way of passing arguments to a function. In this method, the
address of an argument is copied into the parameter. Inside the function, the address is used to
access the actual argument used in the call. This means that changes made to the parameter
affect the argument.
By default, C/C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function. Consider the following
program:
int main()
{
int t=10;
printf("%d %d", sqr(t), t);
return 0;

2
Object Oriented Programming
Lecture (1)

}
int sqr(int x)
{
x = x*x;
return(x);
}
In this example, the value of the argument to sqr() , 10, is copied into the parameter x. When
the assignment
x = x*x takes place, only the local variable x is modified. The variable t, used to call sqr() ,
still has the value 10. Hence, the output is 100 10. Remember that it is a copy of the value of
the argument that is passed into the
function. What occurs inside the function has no effect on the variable used in the call.

Creating a Call by Reference


Even though C/C++ uses call by value for passing parameters, you can create a call by
reference by passing a pointer to an argument, instead of the argument itself. Since the address
of the argument is passed to the function, code within the function can change the value of the
argument outside the function. Pointers are passed to functions just like any other value. Of
course, you need to declare the parameters as pointer types. For example, the function swap()
, which exchanges the values of the two integer variables pointed to by its arguments, shows
how.

void swap(int *x, int *y)


{
int temp;
temp = *x; /* save the value at address x in temp */
*x = *y; /* put value at address y into value at address x */
*y = temp; /* put value temp into value at address y */
}
swap() is able to exchange the values of the two variables pointed to by x and y because their
addresses (not their values) are passed. Thus, within the function, the contents of the variables
can be accessed using standard pointer operations, and the contents of the variables used to
call the function are swapped. Remember that swap() (or any other function that uses pointer

3
Object Oriented Programming
Lecture (1)

parameters) must be called with the addresses of the arguments. The following program
shows the correct way to call swap() :

int main()
{
int i=10, j=20;
swap(&i, &j); /* pass the addresses of i and j */
return 0;
}

In this example, the variable i is assigned the value 10 and j is assigned the value 20. Then
swap() is called with the addresses of i and j. (The unary operator & is used to produce the
address of the variables.) Therefore, the addresses of i and j, not their values, are passed into
the function swap() .

Reference Declarations :

Reference declarations, a C++ feature not available in C, declare the identifier to


be an alternative name, or alias, for an object specified in an initialization of the
reference.
Reference declarations allow a simpler form of call-by-reference parameters. Some
examples are
int n;
int& nn = n; // nn is alternative name for n
double a[10];
double& last = a[9]; // last is an alias for a[9]
Declarations of references that are definitions must be initialized and are usually initialized
to simple variables. The initializer is an l value expression, which gives the variable’s
location in memory. In these examples, the names n and nn are aliases for each
other; that is, they refer to the same object. Modifying nn is equivalent to modifying n,
and vice versa. The name last is an alternative to the single array element a[9]. These
names, once initialized, cannot be changed.
When a variable i is declared, it has an address and memory associated with it. When a

4
Object Oriented Programming
Lecture (1)

pointer variable p is declared and initialized to &i, it has an identity separate from i.
The pointer p has memory associated with it that is initialized to the address of i. When
a reference variable r is declared and initialized to i, it is identical to i. It does not have
an identity separate from the other names for the same object. In effect, r is just
another name for i, that is, an alias.
The following definitions are used to demonstrate the use of dereferencing and aliasing.
The definitions assume that memory at location 1004 is used for integer variable a
and that memory at 1008 is used for pointer variable p.
int a = 5; // declare and define a
int* p = &a; // p points to a
int& ref_a = a; // alias for a
Notice in the preceding figure of pointer declarations that any change to the value of a
is equivalent to changing ref_a. Such a change affects the dereferenced value of p. The
pointer p can be assigned another address and lose its association with a. However, a
and ref_a are aliases and within scope must refer to the same object. These declarations
can be used for call-by-reference arguments, which allows C++ to have call-by-reference
arguments directly. The function order(), using this mechanism, is recoded as
follows:

In file order2.cpp
void order(int& p, int& q)
{
int temp;
if (p > q)
{
temp = p;
p = q;
q = temp;
}
}

int main()
{
int i, j;

5
Object Oriented Programming
Lecture (1)

·····
order(i, j);
·····
}
If i and j are int variables, then order(i, j) uses the reference to i and the reference
to j to exchange, if necessary, their two values. In traditional C, this operation
must be accomplished by using pointers and dereferencing.

Function Returning Value :

All functions, except those of type void, return a value. This value is specified by the
return statement. In C, if a non-void function does not explicitly return a value via a return
statement, then a garbage value is returned. In C++, a non-void function must contain a
return statement that returns a value. That is, in C++, if a function is specified as returning a
value, any return statement within it must have a value associated with it. However, if
execution reaches the end of a non-void function, then a garbage value is returned. Although
this condition is not a syntax error, it is still a fundamental error and should be avoided. As
long as a function is not declared as void, you may use it as an operand in an expression.
Therefore, each of the following expressions is valid:
x = power(y);
if(max(x,y) > 100) printf("greater");
for(ch=getchar(); isdigit(ch); ) ... ;
As a general rule, a function cannot be the target of an assignment. A statement such as
swap(x,y) = 100; /* incorrect statement */
is wrong. The C/C++ compiler will flag it as an error and will not compile a program that
contains it. Sometimes, functions that really don't produce an interesting result return
something anyway. For example, printf() returns the number of characters written. Yet it
would be unusual to find a program that actually checked this. In other words, although all
functions, except those of type void, return values, you don't have to use the return value for
anything. A common question concerning function return values is, "Don't I have to assign
this value to some variable since a value is being returned?" The answer is no. If there is no
assignment specified, the return value is simply discarded. Consider the following program,
which uses the function mul() :
int mul(int a, int b);

6
Object Oriented Programming
Lecture (1)

int main()
{
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */
return 0; }
int mul(int a, int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z. In line 2, the return value is not actually
assigned, but it is used by the printf() function. Finally, in line 3, the return value is lost
because it is neither assigned to another variable nor used as part of an expression.

You might also like