0% found this document useful (0 votes)
15 views112 pages

Lecture 02

The document outlines the content of Lecture 02 for CS352, focusing on C++ expressions, statements, arrays, and pointers. It includes examples of reading and writing data, compiling and executing programs, and using streams and namespaces. Additionally, it covers data types, variables, operators, and initialization methods in C++.

Uploaded by

hbqubit
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)
15 views112 pages

Lecture 02

The document outlines the content of Lecture 02 for CS352, focusing on C++ expressions, statements, arrays, and pointers. It includes examples of reading and writing data, compiling and executing programs, and using streams and namespaces. Additionally, it covers data types, variables, operators, and initialization methods in C++.

Uploaded by

hbqubit
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/ 112

CS352 – OOP & Data Structures

Dr. V. Vijaya Saradhi,


Dept. Of CSE,
IIT Guwahati
[email protected]
Lecture 02: C++ Expressions, Statements, Arrays & Pointers
Overview

● First example program

● Reading data from standard input

● Writing data to standard output

● Compiling & executing program

● Use of streams

● Use of namespace

3
First example program
Example - 01
#include<iostream>
#include<stdio.h>
● Reading int from standard input
int main(int argc, char *argv[])
● A C++ program that uses printf and {
scanf statements int v1;
scanf("%d", &v1);
● stdio.h is part of standard C library Printf("%d\n", v1);
}
● It provides functions for performing
input and output operations. Compiling
$ gcc hello.c -g
● printf, scanf, putchar, getchar
Executing
$ ./a.out
5
Example - 02

#include<iostream>
● Formatting specification rests on user #include<stdio.h>

● To read int use %d in scanf/printf int main(int argc, char *argv[])


{
● To read char use %c in scanf/printf int v1; char c1; float f1;
scanf("%d", &v1);
● To read float use %f in scanf/printf
scanf("%c", &c1);
scanf("%f", &f1);

6
Example - 03

#include<iostream>
● Errors cannot be handled by these functions #include<stdio.h>

● Number of format specifiers must int main(int argc, char *argv[])


match number of arguments {
int v1; char c1;
● Use of scanf and printf are rigid scanf("%c", &v1); // error
scanf("%d", v1); // error
scanf("%d %c", v1); // error
scanf("%d %c", c1); // error
}

7
Example - 04
#include<iostream>
using namespace std;
● iostream is part of the C++ standard
int main(int argc, char *argv[])
library.
{
int v1;
● It provides stream classes for cin >> v1;
performing input and output operations count << v1;
using an object-oriented approach. }

● Frequently used streams


Compiling
● cin, cout, cerr, clog $ g++ hello.cc -g

● These are defined in namespace std Executing


$ ./a.out
8
Example - 05
#include<iostream>
// without using namespace
● iostream is part of the C++ standard
library. int main(int argc, char *argv[])
{
int v1;
● It provides stream classes for
std::cin >> v1;
performing input and output operations
std::count << v1;
using an object-oriented approach. }

● Frequently used streams

● cin, cout, cerr, clog

● These are defined in namespace std

9
Example - 06
#include<iostream>
// without using namespace
● Without using namespace std and
int main(int argc, char *argv[])
{
● Without std::cin or
int v1;
cin >> v1;
● std::cout
count << v1;
}
● Statements results in error

10
Example - 07
#include<iostream>

int main(int argc, char *argv[])


● The operator << is bitwise left shift
{
int v1 = 1 << 3;
● The operator >> is bitwise right shift
printf("%d\n", v1)
}
● 1 << 3 = 8

0 0 0 0 0 0 0 1
128 64 32 16 8 4 2 1

1 << 3
0 0 0 0 1 0 0 0
128 64 32 16 8 4 2 1

11
Example - 08

● The bitwise operators <<, >> when used with such as cin >> v1

● Or when used with cout << v1 perform the I/O operations

● They provides a more intuitive and readable syntax compared to stdio.h

cout << "Value of v1 is" << v1 << endl;

printf("Value of v1 is %d\n", v1);

12
Example - 09

● Reading inputs from a file

● Assume that you have a data


file containing three lines,
one integer per line

● File name is "input.txt"

● 10
● 20
● 30 .a.out < input.txt

Indirection operator

13
Data Types
Overview

● Basic data types ● Basic data types - char, int, float, double, void, bool

● Modifying basic data types ● Modifiers: signed, unsigned, long, short

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

15
Overview

16
Identifiers & Variables
Overview

● Basic data types ● The names of variables, functions, labels, and user-
defined objects are called identifiers.
● Modifying basic data types
● Name can be one or more characters long
● Identifier names
● First character must be from the set: {a, …, z, A, …,
● Variables
Z, _}
● Variable initialization
● Cannot have spaces or special characters like $, !,
● Operators #, %, :, ::, -, -> etc.

● Expressions

18
Overview

● Basic data types ● A variable is a named location in memory that is


used to hold a value.
● Modifying basic data types
type variable_list;
● Identifier names
int i, j, k, l;
● Variables
short int si;
● Variable initialization
unsigned int ui;
● Operators
double d;
● Expressions

19
Overview

● Basic data types ● Global variables are declared outside of all


functions and are accessible from any part of the
● Modifying basic data types code after their declaration

● Identifier names #include<iostream>


using namespace std;
● Variables
int j = 10; // global variable
● Variable initialization
int main(int argc, char *argv[])
● Operators {
cout << j;
● Expressions }

20
Overview

● Basic data types ● Local variables are declared inside a function and can
only be accessed within that function
● Modifying basic data types

● Identifier names #include<iostream>


using namespace std;
● Variables
int main(int argc, char *argv[])
● Variable initialization {
int j = 10; // local variable
● Operators cout << j;
}
● Expressions

21
Overview
● Static variables: retain their value between function
calls. They are initialized only once.
● Basic data types
#include<iostream>
● Modifying basic data types
using namespace std;
void example()
● Identifier names {
static int v1 = 0;
● Variables
v1 = v1 + 1;
cout << v1;
● Variable initialization
}

● Operators
int main(int argc, char *argv[])
{
● Expressions
example();
example();
example();
22
}
Overview
● Static global variables: global variables which are
static declared outside function.
● Basic data types
#include<iostream>
● Modifying basic data types
using namespace std;
void example()
● Identifier names {
static int v1 = 0;
● Variables
v1 = v1 + 1;
cout << v1;
● Variable initialization
}

● Operators
int main(int argc, char *argv[])
{
● Expressions
example();
example();
example();
23
}
Overview
● Static global variables: global variables which are
static declared outside function.
● Basic data types
#include<iostream>
● Modifying basic data types
using namespace std;
static int v1 = 0;
● Identifier names
void example01()
● Variables
{
v1 = v1 + 1;
● Variable initialization
cout << v1;
}
void example02()
● Operators
{
v1 = v1 + 1;
● Expressions
cout << v1;
}
24
Overview
● Static global variables: global variables which are
static declared outside function.
● Basic data types
int main(int argc, char *argv[])
● Modifying basic data types
{
example01();
● Identifier names example01();
cout << v1 << endl;
● Variables
example02();
example02()
● Variable initialization
cout << v1 << endl;
}
● Operators
v1: 4
● Expressions

25
Overview
● Static global variables: global variables which are
static declared outside function.
● Basic data types
Declaration Inside function Outside function
● Modifying basic data types
Scope Within function Within current file
● Identifier names Reinitialization Only once Only once

● Variables

● Variable initialization

● Operators

● Expressions

26
Overview
● Function parameters: treated as local variables

● Basic data types

● Modifying basic data types

● Identifier names void main(int a, int b)


{
● Variables // add two local variables
}
● Variable initialization

● Operators

● Expressions

27
Overview
● Constant variables

● Declared with key word const


● Basic data types
● Must be initialized at the time of declaration.
● Modifying basic data types
● Read-only after initialization.
● Identifier names

● Variables

● Variable initialization
const int max_marks = 100;
● Operators

● Expressions

28
Overview
● External variable

● File1.cc -- counter
● Basic data types
● File2.cc -- variable counter in file1.cc is reused by stating
● Modifying basic data types ● extern int counter;

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

29
Overview
● External variable

● File1.cc -- counter
● Basic data types
● File2.cc -- variable counter in file1.cc is reused by stating
● Modifying basic data types ● extern int counter;

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

30
Overview
● External variable

● File1.cc -- counter
● Basic data types
● File2.cc -- variable counter in file1.cc is reused by stating
● Modifying basic data types ● extern int counter;

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

g++ file1.cc file2.cc main.cc


31
Overview
● Assigning value to variable.

● Basic data types


int i1 = 10; // assign a value
● Modifying basic data types
char c1 = 'A'; // assign a value
● Identifier names
// assign return value from a function
● Variables
int i2 = example(p1);

● Variable initialization
i2 = i1 * 10 + example(p1);//expression

● Operators

● Expressions

32
Overview
● Local variable initialization methods

● Basic data types


int x = 10; --> Copy initialization
● Modifying basic data types
int y(20); --> Direct initialization
● Identifier names
int z{30}; --> Uniform initialization
● Variables

● Variable initialization
We will understand first two when
discussing constructors.
● Operators
Last one prevents narrowing datatypes
● Expressions
int c{3.14}; This is not allowed.
33
Operators
Overview
● Arithmetic operators

● Basic data types


+, -, *, /, %, ++, --
● Modifying basic data types

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

35
Overview
● Relational operators

● Basic data types


==, !=, <, <=, >, >=
● Modifying basic data types

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

36
Overview
● Logical operators

● Basic data types


&& (and)
● Modifying basic data types
|| (or)
! (not)
● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

37
Overview
● Bitwise operators

● Basic data types


& (bitwise and)
● Modifying basic data types
| (bitwise or)
^ (bitwise xor)
● Identifier names ~ (bitwise not)
<< left shift
● Variables
>> right shift

● Variable initialization

● Operators

● Expressions

38
Overview
● Assignment operators

● Basic data types


= (assign)
● Modifying basic data types
+= (add and assign)
-= (subtract and assign)
● Identifier names *= (multiply and assign)
/= (divided by and assign)
● Variables
%= (modulus and assign)
<<= (left shift and assign)
● Variable initialization
>>= (right shift and assign)
&= (bitwise and, assign)
|= (bitwise or and assign)
● Operators
^= (bitwise xor and assign)
● Expressions

39
Overview
● Conditional operator

● Basic data types


int a = 10, b = 20;
● Modifying basic data types
int max = (a > b) ? a : b;
● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

40
Overview
● Increment/decrement operator

● Basic data types


int a = 10, b = 20;
● Modifying basic data types
a++;
● Identifier names b--;

● Variables

● Variable initialization

● Operators

● Expressions

41
Overview
● scope resolution operator

● Basic data types


std::cout << variable;
● Modifying basic data types

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

42
Overview
● Member access operators

● Basic data types


. (DOT) Used to access members of a structure or
● Modifying basic data types class.

● Identifier names -> (arrow) Used to access members of a structure or


class through a pointer.
● Variables

● Variable initialization

● Operators

● Expressions

43
Overview
● Pointer operators

● Basic data types


* Used to access the value at the address a pointer
● Modifying basic data types is pointing to

● Identifier names & Used to get the address of a variable

#include<iostream>
● Variables
use namespace std;

● Variable initialization int main(int argc, char *argv[])


{
● Operators int source = 10;
int *m;
● Expressions m = &source;
int target = *m;
}
44
Overview
● new, delete operators

● Basic data types


Discussed shortly
● Modifying basic data types

● Identifier names

● Variables

● Variable initialization

● Operators

● Expressions

45
Expressions
Overview
● Arithmetic expressions
#include <iostream>
● Basic data types
int main(int argc, char *argv[])
● Modifying basic data types {
int a = 10;
int b = 5;
● Identifier names
int sum = a + b;
int difference = a - b;
● Variables int product = a * b;
int quotient = a / b;
● Variable initialization int remainder = a % b;

std::cout << sum << std::endl;


● Operators std::cout << difference << std::endl;
std::cout << product << std::endl;
std::cout << quotient << std::endl;
● Expressions std::cout << remainder << std::endl;

return 0;
} 47
Overview
● Relational expressions
#include <iostream>
● Basic data types
int main(int argc, char *argv[])
{
● Modifying basic data types int a = 10;
int b = 5;

● Identifier names bool isEqual = (a == b);


bool isNotEqual = (a != b);
bool isGreater = (a > b);
● Variables bool isLess = (a < b);
bool isGeQ = (a >= b);
bool isLeQ = (a <= b);
● Variable initialization
std::cout << "Is =: " << isEqual << std::endl;
std::cout << "Is !=: " << isNotEqual << std::endl;
● Operators std::cout << "Is >: " << isGreater << std::endl;
std::cout << "Is <: " << isLess << std::endl;
std::cout << "Is >=: " << isGeQ<< std::endl;
● Expressions std::cout << "Is <=: " << isLeQ<< std::endl;

return 0;
} 48
Overview
● Logical expressions

● Basic data types


#include <iostream>

● Modifying basic data types int main(int argc, char *argv[])


{
bool a = true;
● Identifier names bool b = false;

● Variables bool logicalAnd = a && b;


bool logicalOr = a || b;
bool logicalNotA = !a;
● Variable initialization
std::cout << "AND: " << logicalAnd << std::endl;
● Operators std::cout << "OR: " << logicalOr << std::endl;
std::cout << "NOTA:"<< logicalNotA <<std::endl;

● Expressions return 0;
}

49
Overview
● Bitwise expressions
#include <iostream>
● Basic data types
int main(int argc, char *argv[])
{
● Modifying basic data types int a = 6; // 0110
int b = 3; // 0011

● Identifier names int bitwiseAnd = a & b;


int bitwiseOr = a | b;
int bitwiseXor = a ^ b;
● Variables int bitwiseNot = ~a;
int leftShift = a << 1;
int rightShift = a >> 1;
● Variable initialization
std::cout << "AND: " << bitwiseAnd << std::endl;
std::cout << "OR: " << bitwiseOr << std::endl;
● Operators std::cout << "XOR: " << bitwiseXor << std::endl;
std::cout << "NOT: " << bitwiseNot << std::endl;
std::cout << "Left: " << leftShift << std::endl;
● Expressions std::cout << "Right: " << rightShift << std::endl;

return 0;
50
}
Overview
● Assignment expressions
#include <iostream>
● Basic data types
int main(int argc, char *argv[])
{
● Modifying basic data types int a = 10;
int b = 5;

● Identifier names a += b;
std::cout << "a += b: " << a << std::endl;
a -= b;
● Variables
std::cout << "a -= b: " << a << std::endl;

● Variable initialization a *= b;
std::cout << "a *= b: " << a << std::endl;

● Operators a /= b;
std::cout << "a /= b: " << a << std::endl;
● Expressions
a %= b;
std::cout << "a %= b: " << a << std::endl;
return 0;
51
}
Overview
● Conditional expressions
#include <iostream>
● Basic data types using namespace std;

● Modifying basic data types int main(int argc, char *argv[])


{
● Identifier names int a = 10;
int b = 20;
● Variables
int max = (a > b) ? a : b;
● Variable initialization
std::cout << max << std::endl;

● Operators
return 0;
}
● Expressions

52
Overview
● Scope resolution expressions
#include <iostream>
● Basic data types using namespace std;

● Modifying basic data types int a = 5;

● Identifier names int main(int argc, char *argv[])


{
int a = 10;
● Variables
cout << "Local a: " << a << endl;
● Variable initialization cout << "Global a: " << ::a << endl;

● Operators return 0;
}
● Expressions

53
Conditional statements, loops
Overview
● If statement
#include <iostream>
● Conditional statements using namespace std;

● Loop structures int main(int argc, char *argv[])


{
int number = 10;
● Jump statements
if (number > 5)
● Block statements {
cout << "number > 5." << endl;
}
else
{
cout << "number <= 5." << endl;
}

return 0;
} 55
Overview ● Nested if statements
#include <iostream>
using namespace std;

int main(int argc, char *argv[])


{
● Conditional statements int age = 20;
bool hasLicense = true;
if (age >= 18)
{
● Loop structures if (hasLicense)
{
cout << "You are eligible to drive." << endl;
}
● Jump statements else
{
cout << "You need a driving license" << endl;
}
● Block statements }
else
{
if (age >= 16)
{
cout << "eligible for a learner's permit." << endl;
}
else
{
std::cout << "Too young to drive." << endl;
}
}

return 0;
56
}
Overview ● Switch statement
#include <iostream>

int main(int argc, char *argv[])


{
int day = 3;
● Conditional statements switch (day) {
case 1:
std::cout << "Monday" << std::endl;
● Loop structures break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
● Jump statements case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
● Block statements std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
break;
case 6:
std::cout << "Saturday" << std::endl;
break;
case 7:
std::cout << "Sunday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
break;
} 57
return 0;
Overview
● For loop
● Conditional statements
#include <iostream>
using namespace std;
● Loop structures
int main(int argc, char *argv[])
{
● Jump statements for (int i = 0; i < 5; i++)
{
● Block statements cout << "Iteration " << i << endl;
}

return 0;
}

58
Overview
● While loop
● Conditional statements

● Loop structures #include <iostream>


using namespace std;

● Jump statements int main()


{
int i = 0;
● Block statements while (i < 5)
{
cout << "Iteration " << i << endl;
i++;
}

return 0;
}

59
Overview

● Do-While loop
● Conditional statements

● Loop structures #include <iostream>


using namespace std;
● Jump statements
int main(nt argc, char *argv[])
{
● Block statements int i = 0;
do
{
cout << "Iteration " << i << endl;
i++;
} while (i < 5);

return 0;
}

60
Jump statements
Overview ● Jump statements

#include <iostream>
● Conditional statements using namespace std;

● Loop structures int main(int argc, char *argv[])


{
for (int i = 0; i < 10; i++)
● Jump statements {
if (i == 5)
{
● Block statements break; // jump statement
}
cout << "Iteration " << i << endl;
}

return 0;
}

62
Overview
● Jump statements
● Conditional statements

#include <iostream>
● Loop structures using namespace std;

int main(int argc, char *argv[])


● Jump statements
{
for (int i = 0; i < 10; i++)
● Block statements {
if (i == 5)
{
continue; // jump statement
}
cout << "Iteration " << i << endl;
}

return 0;
}
63
Block structure statements
Overview
● Block statements
● Conditional statements
#include <iostream>
Using namespace std;
● Loop structures
int main(int argc, char *argv[])
{
● Jump statements int number = 10;

// new block
● Block statements {
int iNumber = 5;
cout << "inner: " << iNumber << endl;
}

cout << "Outer: " << number << endl;

return 0;
}

65
Arrays
Overview ● Static one dimensional arrays
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int arr[5];
arr[0] = 1;
● Declare & Initialize arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
● Partial initialize arr[4] = 5;

for (int i = 0; i < 5; i++)


● Default initialization {
std::cout << arr[i] << " ";
}
● Dynamic array declaration
return 0;
}

67
Overview ● Declare & initialize
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int arr[5] = {1, 2, 3, 4, 5};

● Declare & Initialize for (int i = 0; i < 5; i++)


{
std::cout << arr[i] << " ";
● Partial initialize }

return 0;
● Default initialization }

● Dynamic array declaration

68
Overview ● Partial initialization
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int arr[5] = {1, 2}; // rest 0

● Declare & Initialize for (int i = 0; i < 5; i++)


{
std::cout << arr[i] << " ";
● Partial initialize }

return 0;
● Default initialization }

● Dynamic array declaration

69
Overview ● Default initialization
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int arr[5] = {}; // all elements 0

● Declare & Initialize for (int i = 0; i < 5; i++)


{
std::cout << arr[i] << " ";
● Partial initialize }

return 0;
● Default initialization }

● Dynamic array declaration

70
Overview ● Dynamic array declaration
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int *arr = NULL;
arr = (int *) malloc(5 * sizeof(int) );
● Declare & Initialize
for (int i = 0; i < 5; i++)
{
● Partial initialize arr[i] = 10 + i;
}

● Default initialization for (int i = 0; i < 5; i++)


{
std::cout << arr[i] << " ";
● Dynamic array declaration }

return 0;
}

71
Overview ● Dynamic array declaration
#include <iostream>

int main(int argc, char *argv[])


{
● Static array declaration int *arr = new int[5];
for (int i = 0; i < 5; i++)
● Declare & Initialize {
arr[i] = 10 + i;
}
● Partial initialize
for (int i = 0; i < 5; i++)
{
● Default initialization std::cout << arr[i] << " ";
}

● Dynamic array declaration return 0;


}

72
Overview

new operator malloc function


● new is type-safe and returns a pointer of ● malloc returns a void* that must be cast
the appropriate type, eliminating the to the desired type.
need for explicit casting.

int *arr = new int[5]; arr = (int *) malloc(5 * sizeof(int));

73
Overview

new operator malloc function


● new can initialize the allocated memory, ● malloc does not initialize memory
including calling constructors for
objects.

74
Overview

new operator malloc function


● Memory allocated with new must be ● Memory allocated with malloc must be
deallocated with delete or delete[], deallocated with free

● delete calls destructors for class ● free does not call destructors.
objects.

int *arr = new int[5]; arr = (int *) malloc(5 * sizeof(int));

delete[] arr; free(arr);

75
Overview

● Other methods of array declaration and initialization

● Using STL class array

● Using vector

● We will discuss these two methods after the theme "class" and "template"

76
Two dimensional Arrays
Overview ● Static two dimensional arrays

● Static 2D array declaration

● Declare & Initialize

● Partial initialize

● Dynamic array declaration

78
Overview ● Static 2D arrays – declare & initialize

● Static 2D array declaration

● Declare & Initialize

● Partial initialize

● Dynamic array declaration

79
Overview ● Partial initialization of 2D arrays

● Static 2D array declaration

● Declare & Initialize

● Partial initialize

● Dynamic array declaration

80
Overview ● Dynamic 2D arrays

● Static 2D array declaration

● Declare & Initialize

● Partial initialize

● Dynamic array declaration

81
Pointers
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

83
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

84
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

85
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

86
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

87
Pointers

● Declaration & De-referencing

● Pointer Assignment

● Pointer Arithmetic

● Pointers & Arrays

● Pointers to pointers

88
Passing Data Using A Pointer
Passing Data Using A Pointer

● Primary reason for passing data using pointer is to allow the function to modify
the data

● The following example shows the utility

90
Passing Data Using A Pointer

91
Passing Data Using A Pointer

92
Passing By Value
Passing Data By Value

● If pointers are not passed, the values will not get swapped.

● Example

94
Passing Data By Value

95
Passing Data By Value

96
Passing A Pointer To A Constant
Passing A Pointer To A Constant

● Passing pointer to constant is common

● Passing the address of the data

● Avoid copying large amounts of data in some cases

● However, with a simple pointer data can be modified

● If this behavior is not desirable, then passing a pointer to a constant is the solution

98
Passing A Pointer To A Constant

99
Passing A Pointer To A Constant

● The following code segment #include <iostream>

will result in compilation error Void function_01(const int *num1, int *num2)
as read only constant pointer {
*num1 = 200;
is modified *num2 = 200;
}
● A type mis-match also result in
compilation error as shown in const int limit = 100;
the example.
function_01(&limit, &limit);

● Another example of type mis-


match const int limit = 100;

function_01(&23, &23);

100
Returning A Pointer
Returning A Pointer

● Returning a pointer from a function is simple

● Specify the return type to be a pointer to the appropriate data type

● Allocate memory within the function using malloc and return its address. The caller
is responsible for de-allocate the returned memory

● Pass an object to the function where it is modified. This makes allocation and de-
allocation the responsibility of the caller.

102
Returning A Pointer

● Allocate memory within a int *allocate_array(int size, int value)


{
function and returning its int *arr = (int *) malloc(size * sizeof(int));
address for(int i = 0; i < size; i++)
{
arr[i] = value;
}
return arr;
}

int *vector = allocate_array(5, 45);


for(int i = 0; i < size; i++)
{
cout << vector[i];
}

103
Returning A Pointer

104
Returning A Pointer

● Issues returning a pointer from a function

● Returning an uninitialized pointer

● Returning a pointer to an invalid address

● Returning a pointer to a local variable

● Returning a pointer but not freeing it

105
Returning A Pointer

● The variable arr is a local int *allocate_array(int size, int value)


{
variable int arr[size];
for(int i = 0; i < size; i++)
{
● It's scope lies within the arr[i] = value;
function }
return arr;
}
● Within the function we can
access any address of arr
array int *vector = allocate_array(5, 45);
for(int i = 0; i < size; i++)
{
● Once the function returns, the cout << vector[i];
}
local variable is no longer valid

106
Returning A Pointer

107
Returning A Pointer

● An alternate approach is to int *allocate_array(int size, int value)


{
make the local variable static static int arr[size];
for(int i = 0; i < size; i++)
{
● It's scope lies within the file arr[i] = value;
}
return arr;
● Within the file we can access }
any address of arr array

● Even after the function returns, int *vector = allocate_array(5, 45);


for(int i = 0; i < size; i++)
the static variable is valid and {
accessible cout << vector[i];
}

108
Pointer To A Pointer
Passing A Pointer To A Pointer

● When a pointer is passed to a function, it is passed by value

● If we want to modify the original pointer and not the copy of the pointer, we need
to pass it as pointer to a pointer.

● Following code segment is an example of passing a pointer to a pointer.

110
Passing A Pointer To A Pointer

● The function will return void allocate_array(int **arr, int size, int value)
{
allocated memory through first *arr = (int *) malloc(size * sizeof(int));
parameter for(int i = 0; i < size; i++)
{
*arr[i] = value;
● To modify the pointer "vector", }
return arr;
we need to pass vector's }
address

int *vector = NULL;


allocate_array(&vector, 5, 45);
for(int i = 0; i < size; i++)
{
cout << vector[i] << endl;
}

111
Passing A Pointer To A Pointer

112

You might also like