0% found this document useful (0 votes)
26 views12 pages

Functions and Pointers

Uploaded by

tikoya2311
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Functions and Pointers

Uploaded by

tikoya2311
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Functions in C++

A function is a set of statements that takes input, does some specific computation, and produces
output. The idea is to put some commonly or repeatedly done tasks together to make a function so
that instead of writing the same code again and again for different inputs, we can call this function.

Why Do We Need Functions?


reducing code redundancy
modular
abstraction

To declare a function that can only be called without any parameter, we should use “void
fun(void)“. As a side note, in C++, an empty list means a function can only be called without
any parameter. In C++, both void fun() and void fun(void) are same.

Friend Function
A friend function is a special function in C++ which in spite of not being a member function of a
class has the privilege to access private and protected data of a class.
A friend function is a non-member function or an ordinary function of a class, which is declared by
using the keyword “friend” inside the class. By declaring a function as a friend, all the access
permissions are given to the function.
The keyword “friend” is placed only in the function declaration but not in the function definition.
When the friend function is called neither the name of the object nor the dot operator is used.
However, it may accept the object as an argument whose value it wants to access.
A friend function can be declared in any section of the class i.e. public, private, or protected.

Parameter Passing Techniques in C++


Basic Terminologies
Function Parameters: These variables, which indicate the data that the function anticipates receiving
when called, are specified in the parameter list of a function.
Actual Parameters: The expressions or values passed in during a function call. When the function is
called, it receives these values as input.
The parameters that the function signature declares. They serve as stand-ins for the values that are
provided in when the function is called.
Parameter Passing Techniques in C++

Pass by Value
In Pass by Value method, a variable’s actual value is copied and then passed to the function
instead of the original variable. As the result, any changes to the parameter inside the function will
not affect the variable’s original value outside the function.
Pass by Reference
In pass-by-reference method, instead of passing the argument itself, we passes the reference of
an argument to the function. This allows the function to change the value of the original argument.

// C++ program to illustrate the use of pass by reference


#include <iostream>
using namespace std;

// function to swap variables


void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}

// driver code
int main()
{
int x = 5;
int y = 10;
cout << "Before swap:\n";
cout << "x = " << x << ", ";
cout << "y = " << y << endl;

// Call the 'swap' function with pass-by-reference


// parameters Values of 'x' and 'y' are modified in the
// calling code because references are used.
swap(x, y);

cout << "After swap:\n";


cout << "x = " << x << ", ";
cout << "y = " << y << endl;
return 0;
}
Pass by Pointers
The pass-by-pointer is very similar to the pass-by-reference method. The only difference is that
we pass the raw pointers instead of reference to the function. It means that we pass the address
of the argument to the function.

// C++ program to illustrate the pass by pointer method.


#include <iostream>
using namespace std;

// function to swap variables


void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}

// driver code
int main()
{

int x = 5;
int y = 10;

// Print the values of 'x' and 'y' before the swap


cout << "Before swap:\n";
cout << "x = " << x << " ,";
cout << "y = " << y << endl;

// Call the 'swap' function with pass-by-pointer


// parameters
// Values of 'x' and 'y' are modified in the calling
// code because pointers are used.
swap(&x, &y);

// Print the values of 'x' and 'y' after the swap


cout << "After swap:\n";
cout << "x = " << x << " ,";
cout << "y = " << y << endl;

return 0;
}
Call By Value vs Call By Reference

Call By Value Call By Reference

While calling a function, instead of passing the


While calling a function, we pass the values
values of variables, we pass the address of
of variables to it. Such functions are known
variables(location of variables) to the function
as “Call By Values”.
known as “Call By References.

In this method, the value of each variable in


In this method, the address of actual variables in
the calling function is copied into
the calling function is copied into the dummy
corresponding dummy variables of the
variables of the called function.
called function.

With this method, the changes made to the


With this method, using addresses we would have
dummy variables in the called function have
access to the actual variables and hence we
no effect on the values of actual variables in
would be able to manipulate them.
the calling function.

In call-by-values, we cannot alter the values In call by reference, we can alter the values of
of actual variables through function calls. variables through function calls.

Values of variables are passed by the Pointer variables are necessary to define to store
Simple technique. the address values of variables.

This method is preferred when we have to


This method is preferred when we have to pass a
pass some small values that should not
large amount of data to the function.
change.

Call by value is considered safer as original Call by reference is risky as it allows direct
data is preserved. modification in original data.

Inline Functions in C++


C++ provides inline functions to reduce the function call overhead. An inline function is a function that
is expanded in line when it is called. When the inline function is called whole code of the inline function
gets inserted or substituted at the point of the inline function call. This substitution is performed by the
C++ compiler at compile time. An inline function may increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}

Remember, inlining is only a request to the compiler, not a command. The compiler can ignore the
request for inlining.

The compiler may not perform inlining in such circumstances as:

If a function contains a loop. (for, while and do-while)


If a function contains static variables.
If a function is recursive.
If a function return type is other than void, and the return statement doesn’t exist in a function
body.
If a function contains a switch or goto statement.
Inline function and classes
It is also possible to define the inline function inside the class. In fact, all the functions defined inside
the class are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you
need to explicitly declare an inline function in the class then just declare the function inside the class
and define it outside the class using the inline keyword.

C++ Pointers
A Pointer in C/C++ is a special type of variable that stores the memory address of another variable.
Instead of holding a value directly, a pointer "points" to where a value is stored in memory.

In C and C++, pointers have their own data types, which are determined by the type of the variable
they point to. The type of a pointer specifies the type of data the pointer is intended to point to. Here
are some examples:

Pointer Type Description

int* Pointer to an integer

float* Pointer to a float

double* Pointer to a double

char* Pointer to a char

void* Pointer to any type (generic pointer)


Pointer Type Description

int** Pointer to a pointer to an integer

int (*ptr)[N] Pointer to an array of integers of size N

int (*func)() Pointer to a function returning an integer

Dangling, Void , Null and Wild Pointers in C


Dangling (when pointing to deallocated memory)
Void (pointing to some data location that doesn’t have any specific type)
Null (absence of a valid address)
Wild (uninitialized) pointers.

Dangling Pointer in C
A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.

Void Pointer in C
Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage,
which doesn’t have any specific type. Void refers to the type. Basically, the type of data that it points to
can be any. Any pointer type is convertible to a void pointer hence it can point to any value.

Note: Void pointers cannot be dereferenced. It can however be done using typecasting the void
pointer. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and
thus size.

NULL Pointer in C
NULL Pointer is a pointer that is pointing to nothing(i.e. not pointing to any valid object or memory
location). In case, if we don’t have an address to be assigned to a pointer, then we can simply use
NULL. NULL is used to represent that there is no valid memory address.

Note NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null
pointer stores a defined value, but one that is defined by the environment to not be a valid
address for any member or object. NULL vs Void Pointer – Null pointer is a value, while void
pointer is a type

A NULL pointer explicitly points to no valid memory address, whereas an uninitialized pointer
contains an unpredictable memory address.
A NULL pointer explicitly points to no valid memory address, while a void pointer is a type of
pointer that can point to any data type but doesn't have a specific type itself.

NULL Pointer: A special value used to indicate that the pointer is not currently pointing to any
valid memory location. This is useful for initialization and for error checking before dereferencing
pointers.
Value of NULL : Represents a pointer that does not point to any valid memory location, usually
defined as zero (0).

Wild pointer in C
A pointer that has not been initialized to anything (not even NULL) is known as a wild pointer. The
pointer may be initialized to a non-NULL garbage value that may not be a valid address.

Syntax
dataType *pointerName;

Applications of Pointers in C
1. Passing Arguments by Reference
i. to modify the variable in another function.
ii. For Efficiency Purpose: Passing large structure without reference would create a copy of the
structure (hence wastage of space).
2. For Accessing Array Elements
3. To Return Multiple Values
4. For dynamic memory Allocation

Pointer is used in the following cases


i) It is used to access array elements
ii) It is used for dynamic memory allocation.
iii) It is used in Call by reference
iv) It is used in data structures like trees, graph, linked list etc.

Can References Refer to Invalid Location in C++?


In C++, references cannot be null or uninitialized, meaning they must always refer to a valid memory
location. However, if the referenced object is deleted or goes out of scope, the reference can become
invalid, leading to undefined behavior if accessed.
Characteristics References Pointers

The variable cannot be The variable can be reassigned in


Reassignment
reassigned in Reference. Pointers.

Memory It shares the same address as the Pointers have their own memory
Address original variable. address.

Work It is referring to another variable. It is storing the address of the variable.

Null Value It does not have null value. It can have value assigned as null.

This variable is referenced by the The pointer does it work by the method
Arguments
method pass by value. known as pass by reference.

Important
When to use What
The performances are exactly the same as references are implemented internally as pointers. But still,
you can keep some points in your mind to decide when to use what:

Use references:

In function parameters and return types.

Use pointers:

If pointer arithmetic or passing a NULL pointer is needed. For example, for arrays (Note that
accessing an array is implemented using pointer arithmetic).
To implement data structures like a linked list, a tree, etc. and their algorithms. This is so because,
in order to point to different cells, we have to use the concept of pointers.

Passing By Pointer vs Passing By Reference in C++

Parameters Pass by Pointer Pass by Reference

Passing We pass the address of arguments in We pass the arguments in the


Arguments the function call. function call.

Accessing The value of the arguments is accessed The reference name can be used
Values via the dereferencing operator *. to implicitly reference a value.
Parameters Pass by Pointer Pass by Reference

Passed parameters can be Parameters can’t be


Reassignment moved/reassigned to a different memory moved/reassigned to another
location. memory address.

Pointers can contain a NULL value, so a References cannot contain a


Allowed Values passed argument may point to a NULL NULL value, so it is guaranteed to
or even a garbage value. have some value.

Difference Between Reference Variable and Pointer Variable


A reference is the same object, just with a different name and a reference must refer to an object.
Since references can’t be NULL, they are safer to use.

A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.
The pointer can be assigned NULL directly, whereas the reference cannot.
Pointers can iterate over an array, we can use increment/decrement operators to go to the
next/previous item that a pointer is pointing to.
A pointer is a variable that holds a memory address. A reference has the same memory address
as the item it references.
A pointer to a class/struct uses ‘->’ (arrow operator) to access its members whereas a reference
uses a ‘.’ (dot operator)
A pointer needs to be dereferenced with * to access the memory location it points to, whereas a
reference can be used directly.

Which is preferred, Passing by Pointer Vs Passing by Reference in C++?


References are usually preferred over pointers whenever we don’t need “reseating”.
If we want to use NULL in our function arguments, prefer pointers.
Overall, Use references when you can, and pointers when you have to.

References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A
variable can be declared as a reference by putting ‘&’ in the declaration.

References vs Pointers

1. A pointer can be declared as void but a reference can never be void For example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid

1. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer,
triple-pointer. Whereas, the reference variable has only one/single level of indirection.
2. Reference variables cannot be updated.
3. Reference variable is an internal pointer.
4. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as
“address of”).

Understanding nullptr in C++

// C++ program to demonstrate problem with NULL


#include <bits/stdc++.h>
using namespace std;

// function with integer argument


void fun(int N) { cout << "fun(int)"; return;}

// Overloaded function with char pointer argument


void fun(char* s) { cout << "fun(char *)"; return;}

int main()
{
// Ideally, it should have called fun(char *),
// but it causes compiler error.
fun(NULL);
}

Output:

16:13: error: call of overloaded 'fun(NULL)' is ambiguous


fun(NULL);

What is the problem with above program?


NULL is typically defined as (void *)0 and conversion of NULL to integral types is allowed. So the
function call fun(NULL) becomes ambiguous.
How does nullptr solve the problem?
In the above program, if we replace NULL with nullptr, we get the output as “fun(char *)”.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is
implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or
comparable to integral types.
As a side note, nullptr is convertible to bool.

You might also like