0% found this document useful (0 votes)
45 views

Week 3-4

The document discusses functions, pointers, and arrays in C/C++. It covers defining and calling functions, passing arguments, return values, storage classes, and pointers including pointer arithmetic and accessing array elements using pointers. It also discusses recursion, inline functions, default arguments, and constant pointers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Week 3-4

The document discusses functions, pointers, and arrays in C/C++. It covers defining and calling functions, passing arguments, return values, storage classes, and pointers including pointer arithmetic and accessing array elements using pointers. It also discusses recursion, inline functions, default arguments, and constant pointers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

WEEK 3_4

• Functions
• Pointers

• REF: . Kunal Pimparkhede - Computer Programming with C++ (2016, Cambridge


University Press).
Functions
• As the size of the program increases, the code becomes more prone to
errors and the debugging of the program becomes difficult.

• In C/C++, it is possible to split a large program into multiple independent


pieces.

• Each independent piece is called a function or a method. A function can


define a single operation or a sequence of operations.

• You can invoke a function whenever you need to execute the operations it
defines.

• A function can have multiple inputs (called arguments) and generate a single
output (called return value)
Notes It is also possible to create a function without any arguments and/or return value
Structured programming or modular programming
Calling a function
Creating Functions

Syntax for creating a function


Example: Function definition of add()
Declaration of a function is called function prototype.
Prototyping a function is not necessary if we define the function before main(), it is
mandatory only when the function is defined after main()
Prototype includes the following information about the function:
1. Name of the function
2. Return type of the function
3. Data type and order of the arguments of the function
Prototype of the function add()
Complete program with the function add()prototyped
Call to function add()
Defining the function before main()
Local Variables of the Function

Even main()
cannot access
any variables
defined in any of
the other
functions, such
as add() and
sub()
Functions with Arguments
The values that we pass from the calling function to the called function are referred as
arguments.
Functions with Return Values

• The ‘called’ function can give a single value back to the ‘calling’ function.

• This value sent from the ‘called’ function to the ‘calling’ function is called
a ‘return value’

• The ‘return’ statement in C/C++ is used to send value back to the caller.

• Given below is the syntax of return statement: return ; The statement will return
the result of the expression back to the calling function.
Functions with Return Values

Prototype of function add() returning an integer

NOTES We can only return one value at a time from the ‘called’ function to the
‘calling’ function.
NOTE When return statement is encountered, it ends the execution of the
current function and transfers the control back to the caller immediately.
Execution of return statement
Program to find the maximum of six numbers using the function with two
arguments: An example
Passing Array as an Argument to the Function
finding the maximum of n elements from the array
Recursion
Recursive Function A function that calls itself conditionally is called a recursive
function

Unconditional recursion
Calculating xy using recursion: An example
values of x (base) and y (index) are taken as input from the user. We will create a recursive
function named exp() returns an integer value of xy.
let assume x = 2 , y = 4. We now need to calculate the result of 24 in the program.
The process of inserting elements into the stack is called as pushing whereas the
process of removing elements from stack is called as popping.
Activation frames: How Function Calls and Returns are Internally Handled in C/C++
Each time a function is called, space is created in memory for its execution. This
space is called an activation frame or an activation record.

An activation frame is a data structure which contains four parts:

1. Local variables These are variables declared within the scope of the function.

2. Arguments These are values which the function accepts as arguments.

3. Return value The value returned by the function.

4. Return location This is the address of the statement of caller where the control of
execution should return after the called function ends.
Activation frames are used to handle function calls and returns by the CPU.
RAM Addresses
When a function is called, the activation frame for
the function is created and pushed on the stack
Stack storing activation frames of main(), f1() and f2()
Storage Classes in C/C++
The place in the memory where a variable is stored on its creation is called a
‘storage class’ of that variable.

C/C++ supports following storage classes for each of its variables:


1. auto storage class
2. register storage class
3. static storage class
4. extern storage class

syntax of declaring variables by specifying the ‘storage class’ for the variables
Auto storage class
This is the default storage class for all the variables of C/C++. The variables of type
auto are stored in the main memory (RAM) of the computer system

Register and auto-storage classes


Register storage class
Register refers to the internal memory integrated inside the chip of the processor. The
variables with a storage class specified as register are stored in the internal registers of
the CPU

Static storage class


The static variables are variables whose lifespan is throughout the C/C++ program. Static
variables can only be accessed within a function or a block in which they are defined
Extern storage class
The variable which is defined in some other cpp file is called an external variable.
Inline Functions
• An inline function is a function whose code is substituted in place of the function
call by the compiler
• Hence, the inline functions speed up the execution of the program
• A function can be made inline using a keyword inline in C/C++
Function with Default Arguments (Only in C++ not in C)
A function argument which can take a default value if its value is not provided by
the caller is called a default function argument. The default values of the arguments
must be specified while prototyping the function.
Codes to perform addition of four integers with two of them as default arguments:
Some Built-in Functions
Pointers
Every variable that we create is stored in the main memory of the computer system.

RAM is usually
splitted into
logical
partitions of
64 KB each.
Each logical
partition is
called
segment.
Storage of integer variable in RAM

Every location in RAM is of 1 byte, it requires two consecutive locations in RAM because
size of integer is of 2 bytes.
Creating Pointers

• A pointer is a variable which stores the address of some other variable.

• This means that the value of the pointer will be the memory address of location
which stores the value of another variable.

• The variable whose address is contained in the pointer is called target variable.

• We can access the value of target variable by using a pointer that points to it, this
process is called indirection.

The following is the syntax to create a pointer:


Storage of variable in RAM
Storage of pointer in RAM

the pointer p points to variable a

Pointer pointing to a variable


indirection operator (*)

We can now access the value of variable a by using pointer p


Data Type of Pointers
Data type the pointer must be same as the data type of the variable to which it points to
Types of Function Calls
Call by value
Since value of the variable is passed from calling function to the called function, the
mechanism is named as ‘call by value’

Note: Call by value creates two


different variables at
different physical locations in
memory.
Call by value
Call by address
When a function is called by passing the address of the actual parameters instead of
values, the mechanism is named as ‘call by address’

Argument of function f1() is declared as a


pointer, as it needs to store the address that
is passed by main().
Call by address
To swap the values of two variables by using call by address: An example
Initialization of formal arguments of swap() function
Variable temp is created in swap() function
Execution of temp=*p
Execution of *p=*q
Execution of *q=temp
Arithmetic Operations with Pointers

C/C++ supports usage of following operators for performing operations with the
address that is contained in the pointer:

• Unary operators: ++ (increment) and -- (decrement)


• Binary operators: + (addition) and – (subtraction)

1 0 02

change the address contained inside the pointer, by a factor 1*sizeof(int)


Constant pointer
A pointer which cannot change the address to which it points to is called a constant
pointer.

The following declaration of a constant pointer is illegal, because the pointer p is


never initialized.

is legal because it initializes the address of variable a in


the constant pointer p
Constant pointer
As p is a constant pointer, you cannot change the address stored inside p
Accessing Array Elements using a Pointer

All the elements of an array can be accessed by using a single pointer, if the pointer
stores the starting address of the array
Accessing array elements using pointer p
Notes

In general, *(p+i) will always give the same value as that of a[i] provided the
pointer p stores the starting address of the array

the statement printf("%d",a[i]); is equivalent to printf("%d",*(p+i));

scanf("%d",&a[i]); can be rewritten as scanf("%d",(p+i));

Note that, indirection operator * is not present because scanf()function is always


made by passing address of the variable as an argument to it.
Program to arrange n-numbers in ascending order using
pointers: An example
Initialization of an Array: Revisited

allocate an array space to store 5 integer values


and the starting address of the array in a constant
pointer
The only way to initialize an array after its creation is by initializing one element at a time

This works because it does not change the address in pointer a, but only stores
values in locations of the array.
Making re-initializations work with pointers

will not work will work

Because a is created as a Because p is created as a


constant pointer internally Non constant pointer internally
We know that array of characters can be initialized to a string using the
following syntax:
char arrayname[]="StringConstant";

Works well

Following code will fail, because it applies string initialization to the array after its
creation

Works well
The type cast (int[5]) informs the compiler that the initializer type is an
array of 5 integers
NOTES
A string constant can be initialized to a
character pointer without casting it to array
type. This is because compiler anyway
creates an array of characters to store a
string.
As p is not a constant pointer, it is possible to reinitialize it to another string. For
example, the statement
NOTES When a pointer is initialized, compiler allocates the necessary memory
which stores the data, For example, the statement

will allocate data space of 6 bytes


(5 bytes for characters + 1 byte for null character)

if you do not initialize the pointer p and just declare it with a intention to accept a
string as input from the user, the program will crash
To resolve this issue we must reserve some memory space to store the input data,

The scanf() statement works well because the pointer p holds the starting address of
an 100 byte space in memory before using it to accept a string.
For example, if we initialize an integer pointer z as below:

compiler will allocate the memory of 5 integers. But, if you need to print each
data value pointed by z you must print it one element at a time
Similarly, instead of initializing z to an array if you wish to accept the array values
as input from the user you must follow the following two steps:
Self-addressability of Character Variables

If you try to print the address of a character you will actually get its value.
Characters and Strings in C/C++ are said to be self-addressable.

Let c be a character variable with a value $, the statement

Prints the value $ instead of printing memory address of the character variable

The result of both the statements below is identical


So, how can we print the address of the character variable? This can be done by
changing the control string to %d rather than using %c

Do not confuse this statement with the statement below:

So in summary, using control string as %d and & operator with character variable
will force C/C++ to print the address of a character variable.
If you are a C++ programmer and using cout statement you answer the question
below:

This is because the operator << is overloaded for character type of variables in C++; to
print the value of the variable instead of the address.
The below statement prints the address of the character c by typecasting it to an
integer type of pointer(int*)

Character pointers perform direct initialization of the string constants to a character


type pointer. So, we can directly initialize a string value to the character type pointer,

Now the statement,

will print the string Hello on the computer screen instead of


printing the address
Array of Pointers
It is possible to create an array such that, each element of an array is a pointer

will create an array of


pointers named as p of size 3
Array of Pointers
The given loop will print
the values of three
variables a, b and c
Creating array of strings using 1-D array of character pointers

For example, consider the statement below which creates an 1-D array p of
character pointers of size 3

We can initialize each of the individual pointers p[0],p[1], and p[2] to string values
The following loop will also print each of the individual strings
Pointer to a Pointer

A pointer that stores the address of another pointer is called a ‘Pointer to a Pointer’.
A ‘pointer’ which is pointed by a ‘pointer to pointer’ is called a target pointer and the
data item pointed by target pointer is called target variable.
Pointer to a Pointer
We can now create a pointer q such that, it stores the address of pointer p. Such a
pointer q is called a ‘pointer to a pointer’ because it points to another pointer p. Below
is the syntax for creating a ‘pointer to a pointer’:
Pointers and 2D Arrays
Array of pointers created before representing the matrix by the compiler
Address of individual elements in a matrix
Storage of a 2-D array in computer memory
We can access all the elements of a 2-D array using a single pointer to a pointer.
To illustrate this concept, we will create a 2-D pointer named as p

will store the starting address of 2-D array in 2-D pointer p


Any element of an array a[i][j] can be accessed using pointer p as *(*(p+i)+j)

to access a element a[1][3] using an expression

Substituting the value of p as 1000 in the expression

1014 is an address of a 2 bytes location, therefore 1014+3 is actually evaluated as


1014+3*2=1020

Applying indirection operator on address 1020 will fetch the contents of memory
locations 1020 which is an integer value 80.
Program to perform addition of 2 matrices using pointers: An example
void Pointers
void type pointers can point to a variable of any type void pointers are also called
universal pointers because they have an ability to point to data values of every type.

will make the void type pointer p to point to floating point variable a

attempt to copy the address stored in pointer p to pointer pint, we have to do a type
casting of a void pointer p to integer type as seen in the statement
The code below creates two variables a and b of type int and float, respectively. The
given program uses a void type pointer p to access the value of each of these variables.
Pointer to a Function
Pointers in C/C++ can also point to a function which is defined in the program. To make
a pointer point to a function, type of the pointer must match with the prototype
of the function.

You might also like