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

unit 1 C++ NOTES

The document provides an introduction to C++ programming, detailing its history, features, and comparisons with the C language. It covers key concepts such as data types, variables, constants, user-defined data types, and operators, along with examples of their usage. Additionally, it emphasizes the object-oriented nature of C++ and its capabilities for real-world problem modeling.

Uploaded by

santosh94998
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

unit 1 C++ NOTES

The document provides an introduction to C++ programming, detailing its history, features, and comparisons with the C language. It covers key concepts such as data types, variables, constants, user-defined data types, and operators, along with examples of their usage. Additionally, it emphasizes the object-oriented nature of C++ and its capabilities for real-world problem modeling.

Uploaded by

santosh94998
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIT-1

BCA- 204 Introductions to Object Oriented Programming &


C++

C++ history
 C++ programming language was developed in 1980 by Bjarne Stroustrup
at bell laboratories of AT&T (American Telephone & Telegraph), located in
U.S.A.
 Bjarne Stroustrup is known as the founder of C++ language.

 It was develop for adding a feature of OOP (Object Oriented


Programming) in C without significantly changing the C component

C++ programming is "relative" (called a superset) of C, it means any valid C


program is also a valid C++ program.

LANGUAGE YEAR DEVELOPED BY

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

Kernighan & Dennis


K&RC 1978
Ritchie

C++ 1980 Bjarne Stroustrup


C++ Features
C++ is a widely used programming language.

1) Simple

C++ is a simple language because it provides a structured approach (to break the
problem into parts), a rich set of library functions, data types, etc.

2) Abstract Data types

In C++, complex data types called Abstract Data Types (ADT) can be created
using classes.

3) Portable

C++ is a portable language and programs made in it can be run on different


machines.

4) Mid-level / Intermediate programming language

C++ includes both low-level programming and high-level language so it is known


as a mid-level and intermediate programming language. It is used to develop
system applications such as kernel, driver, etc.
5) Structured programming language

C++ is a structured programming language. In this we can divide the program into
several parts using functions.

6) Rich Library

C++ provides a lot of inbuilt functions that make the development fast. Following
are the libraries used in C++ programming are:

o <iostream>
o <cmath>
o <cstdlib>
o <fstream>

7) Memory Management

C++ provides very efficient management techniques. The various memory


management operators help save the memory and improve the program's
efficiency. These operators allocate and deallocate memory at run time. Some
common memory management operators available C++ are new, delete etc.

8) Quicker Compilation

C++ programs tend to be compact and run quickly. Hence the compilation and
execution time of the C++ language is fast.

9) Pointer

C++ provides the feature of pointers. We can use pointers for memory, structures,
functions, array, etc. We can directly interact with the memory by using the
pointers.

10) Recursion

In C++, we can call the function within the function. It provides code reusability
for every function.

11) Extensible
C++ programs can easily be extended as it is very easy to add new features into the
existing program.

12) Object-Oriented

In C++, object-oriented concepts like data hiding, encapsulation, and data


abstraction can easily be implemented using keyword class, private, public, and
protected access specifiers. Object-oriented makes development and maintenance
easier.

13) Compiler based

C++ is a compiler-based programming language, which means no C++ program


can be executed without compilation. C++ compiler is easily available, and it
requires very little space for storage. First, we need to compile our program using a
compiler, and then we can execute our program.

14) Reusability

With the use of inheritance of functions programs written in C++ can be reused in
any other program of C++. You can save program parts into library files and
invoke them in your next programming projects simply by including the library
files. New programs can be developed in lesser time as the existing code can be
reused. It is also possible to define several functions with same name that perform
different task. For Example: abs () is used to calculate the absolute value of
integer, float and long integer.

15) National Standards

C++ has national standards such as ANSI.

16) Errors are easily detected

It is easier to maintain a C++ programs as errors can be easily located and rectified.
It also provides a feature called exception handling to support error handling in
your program.

17) Power and Flexibility

C++ is a powerful and flexible language because of most of the powerful flexible
and modern UNIX operating system is written in C++. Many compilers and
interpreters for other languages such as FORTRAN, PERL, Python, PASCAL,
BASIC, LISP, etc., have been written in C++. C++ programs have been used for
solving physics and engineering problems and even for animated special effects for
movies.

18) Strongly typed language

The list of arguments of every function call is typed checked during compilation. If
there is a type mismatch between actual and formal arguments, implicit conversion
is applied if possible. A compile-time occurs if an implicit conversion is not
possible or if the number of arguments is incorrect.

19) Redefine Existing Operators

C++ allows the programmer to redefine the meaning of existing operators such as
+, -. For Example, The "+" operator can be used for adding two numbers and
concatenating two strings.

20) Modelling real-world problems

The programs written in C++ are well suited for real-world modeling problems as
close as possible to the user perspective.

21) Clarity

The keywords and library functions used in C++ resemble common English words.

C++ is multi-
C follows
paradigm. It supports
1) the procedural style
both procedural and
programming.
object oriented.
In C++, you can use
modifiers for class
Data is less secured in
2) members to make it
C.
inaccessible for
outside users.

C++ follows
C follows the top-
3) the bottom-up
down approach.
approach.

C does not support C++ supports function


4)
function overloading. overloading.

In C, you can't use In C++, you can use


5)
functions in structure. functions in structure.

C does not support C++ supports


6)
reference variables. reference variables.

C++ mainly uses


In C, scanf() and
stream cin and cout to
7) printf() are mainly
perform input and
used for input/output.
output operations.

Operator overloading Operator overloading


8)
is not possible in C. is possible in C++.

C programs are
C++ programs are
divided
9) divided into functions
into procedures and
and classes.
modules
C does not provide the C++ supports the
10)
feature of namespace. feature of namespace.

Exception handling is C++ provides


not easy in C. It has to exception handling
11)
perform using other using Try and Catch
functions. block.

C does not support the C++ supports


12)
inheritance. inheritance.

Tokens and Identifiers

1.Character Set and Symbols:

C++ language uses a character set that includes:

 Alphanumeric characters: Uppercase (A-Z), lowercase (a-z), and digits (0-


9).
 Special characters: Symbols such as +, -, *, /, =, {}, [], (), ;, :, ,, &, %, and
others.
 Whitespace characters: Spaces, tabs, and newlines used to separate tokens.
 Escape sequences: For example, \n (newline), \t (tab), \\ (backslash), etc.

#include <iostream>

using namespace std;

int main() {

int x = 10;

float y = 3.14;

char ch = 'A'; // Using special characters like 'A'


cout << "Value of x: " << x << ", y: " << y << ", ch: " << ch << endl;

return 0;

2.Keywords:

Keywords are reserved words in C++ that have a special meaning and cannot be
used as identifiers (e.g., variable names).

Examples include:

 int, char, float, double, if, else, for, while, return, switch, etc.

3.Identifiers:

Identifiers are names given to various program elements, such as variables,


functions, arrays, etc. Rules for identifiers:

 Must begin with a letter (A-Z, a-z) or an underscore (_).


 Can include letters, digits (0-9), and underscores.
 Cannot be a keyword.
 C++ is case-sensitive, meaning Variable and variable are different.

Example:

int main() {
int age = 25; // 'age' is an identifier
char grade = 'A'; // 'grade' is an identifier

}
#include <iostream>
using namespace std;

int main() {
int if = 10; // Error: 'if' is a keyword
cout << if << endl;
return 0;
}
Variables and Constants

Variables:

A variable is a named memory location used to store data that can change during
program execution.

Syntax:

data_type variable_name;
Example:

#include <iostream>
using namespace std;

int main() {
int number = 10;
char letter = 'A';
float price = 19.99;
cout << "Number: " << number << ", Letter: " << letter << ", Price: " << price
<< endl;
return 0;
}

Constants:

Constants are values that do not change during program execution. They are
defined using the const keyword. Example:

#include <iostream>
using namespace std;

int main() {
const int MAX_SIZE = 100;
cout << "Maximum size is: " << MAX_SIZE << endl;
// MAX_SIZE = 200; // Error: cannot modify a constant
return 0;
}

Data Types

A data type specifies the type of data that a variable can store such as integer,
floating, character etc.

Basic Data Types:

 Integer Types: int, short, long, long long.


 Floating Point Types: float, double, long double.
 Character Type: char (used to store a single character).
 Boolean Type: bool (stores true or false).

#include <iostream>

using namespace std;

int main() {

int integerVar = 5;

float floatVar = 5.67;


double doubleVar = 3.14159;

char charVar = 'A';

bool boolVar = true;

cout << "Integer: " << integerVar << ", Float: " << floatVar

<< ", Double: " << doubleVar << ", Char: " << charVar

<< ", Boolean: " << boolVar << endl;

return 0;

Arrays and Strings:

 Arrays: A collection of elements of the same type stored in contiguous


memory locations. Example:

int arr[5] = {1, 2, 3, 4, 5};


 Strings: C++ does not have a built-in string type, but strings can be
managed using arrays of characters or the std::string class (from the
Standard Library). Example:

#include <iostream>
using namespace std;

int main() {
int arr[5] = {1, 2, 3, 4, 5};
cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
char str[] = "Hello";
cout << "String: " << str << endl;

return 0;
}
User-Defined Data Types:

Structures: A user-defined data type that groups different types of variables


under a single name. Example:

#include <iostream>

using namespace std;

struct Person {

string name;

int age;

};

int main() {

Person p1 = {"Alice", 30};

cout << "Name: " << p1.name << ", Age: " << p1.age << endl;

return 0;

Unions: A data structure that can store different data types in the same memory
location. Example:

union Data {
int i;
float f;
};
Enumerations: A user-defined data type consisting of a set of named integral
constants. Example:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday };

Operators

Operators in C++ are symbols that perform operations on variables and values.
Some common operators:

Arithmetic Operators: +, -, *, /, %.

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 5;
cout << "Sum: " << (a + b) << endl;
cout << "Difference: " << (a - b) << endl;
cout << "Product: " << (a * b) << endl;
cout << "Division: " << (a / b) << endl;
cout << "Modulus: " << (a % b) << endl;

return 0;
}

Relational Operators: ==, !=, <, >, <=, >=.

#include <iostream>

using namespace std;

int main() {

int a = 10, b = 5;

cout << "a == b: " << (a == b) << endl;


cout << "a != b: " << (a != b) << endl;

cout << "a > b: " << (a > b) << endl;

cout << "a < b: " << (a < b) << endl;

return 0;

Logical Operators: &&, ||, !.

#include <iostream>

using namespace std;

int main() {

bool a = true, b = false;

cout << "a && b: " << (a && b) << endl;

cout << "a || b: " << (a || b) << endl;

cout << "!a: " << !a << endl;

return 0;

Assignment Operators: =, +=, -=, *=, /=.

#include <iostream>

using namespace std;


int main() {

int a = 5;

a += 3; // a = a + 3

cout << "a += 3: " << a << endl;

a *= 2; // a = a * 2

cout << "a *= 2: " << a << endl;

return 0;

Increment (++) and Decrement (--) Operators:

Increment (++): Increases the value of a variable by 1.

o Postfix (variable++): Uses the value first, then increments.

int a = 5;
int b = a++; // b = 5, a = 6 after

o Prefix (++variable): Increments the value first, then uses it.

int a = 5;
int b = ++a; // b = 6, a = 6 after

 Decrement (--): Decreases the value of a variable by 1.


o Postfix (variable--): Uses the value first, then decrements.

int a = 5;
int b = a--; // b = 5, a = 4 after
o Prefix (--variable): Decrements the value first, then uses it.

int a = 5;
int b = --a; // b = 4, a = 4 after

Bitwise Operators: &, |, ^, ~, <<, >>.

 AND (&): Returns 1 only if both bits are 1.


o Example: 5 & 3 → 0001 → Result: 1
 OR (|): Returns 1 if at least one bit is 1.
o Example: 5 | 3 → 0111 → Result: 7
 XOR (^): Returns 1 if bits are different.
o Example: 5 ^ 3 → 0110 → Result: 6
 NOT (~): Inverts all bits.
o Example: ~5 → 1010 (in 4 bits, result is -6)
 Left Shift (<<): Shifts bits to the left, adding 0 on the right.
o Example: 5 << 1 → 1010 → Result: 10
 Right Shift (>>): Shifts bits to the right.
o Example: 5 >> 1 → 0010 → Result: 2

 Conditional (Ternary) Operator: ? :.

The Conditional (Ternary) Operator is a shorthand for an if-else statement. It


allows you to evaluate a condition and return one of two values based on whether
the condition is true or false.

Syntax:

condition ? value_if_true : value_if_false;

 condition: The condition that is evaluated.


 value_if_true: The value returned if the condition is true.
 value_if_false: The value returned if the condition is false.

Example:
int a = 5, b = 10;
int max = (a > b) ? a : b; // If a > b, max = a; else max = b
// Result: max = 10

In this example:

 The condition (a > b) is false, so max will be assigned b (which is 10).

Type Conversions and Type Cast Operators

 Implicit Type Conversion (Type Promotion): Done by the compiler


automatically when converting a smaller type to a larger type,

#include <iostream>

using namespace std;

int main() {

int a = 5;

float b = 2.5;

float result = a + b; // Implicit conversion: int to float

cout << "Result: " << result << endl;

return 0;

 Explicit Type Conversion (Type Casting): Done by the programmer using


type casting. Syntax:

(type) value; // Explicit type cast


Example: #include <iostream>

using namespace std;


int main() {

float f = 9.7;

int i = (int) f; // Explicit conversion: float to int

cout << "Converted value: " << i << endl; // Output will be 9

return 0;

Console I/O: cin and cout

 cin: Used to take input from the user.


 cout: Used to display output to the user.

Examples:

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num; // Taking input from user

cout << "You entered: " << num << endl; // Displaying output

return 0;
}
Control Statements

Control Statements in programming are used to control the flow of execution


based on certain conditions or loops.
if Statement:

if statement: Executes a block of code if a specified condition is true.

if (condition) {
// code to execute if condition is true
}
Ex-
#include <iostream>
using namespace std;

int main() {
int a = 10;
if (a > 5) {
cout << "a is greater than 5" << endl;
}
return 0;
}
if-else Statement:

if-else statement: Executes one block of code if the condition is true and another
block if the condition is false.

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
#include <iostream>
using namespace std;

int main() {
int a = 3;
if (a > 5) {
cout << "a is greater than 5" << endl;
} else {
cout << "a is less than or equal to 5" << endl;
}
return 0;
}
else if Ladder:

Multiple conditions can be checked in sequence.

if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if none of the conditions are true
}
#include <iostream>
using namespace std;

int main() {
int a = 7;
if (a > 10) {
cout << "a is greater than 10" << endl;
} else if (a == 7) {
cout << "a is 7" << endl;
} else {
cout << "a is less than 7" << endl;
}
return 0;
}
switch Statement:

Used to execute one of many blocks of code based on the value of an expression.

switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no match
}
#include <iostream>
using namespace std;

int main() {
int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
case 4: cout << "Thursday"; break;
default: cout << "Invalid day"; break;
}
return 0;
}

Loops:

Loops are used to repeat a block of code multiple times. There are different types
of loops in programming, each with its own use case.

1. for,
2. while,
3. do-while

for Loop:

Used when the number of iterations is known beforehand.

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


// code to execute
}
Ex-
#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
cout << "i = " << i << endl;
}
return 0;
}
while Loop:

Used when the number of iterations is unknown and the loop runs while a
condition is true.

int i = 0;
while (i < 5) {
// code to execute
i++;
}
Ex-#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
cout << "i = " << i << endl;
i++;
}
return 0;
}
do-while Loop:

Similar to the while loop, but it guarantees at least one iteration.

int i = 0;
do {
// code to execute
i++;
} while (i < 5);
Ex-
#include <iostream>
using namespace std;

int main() {
int i = 1;
do {
cout << "i = " << i << endl;
i++;
} while (i <= 5);
return 0;
}
break and continue:

 break: Exits the loop immediately.


 continue: Skips the current iteration and moves to the next one.

Ex-

#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; i++) {

if (i == 3) {

break; // Exit the loop when i == 3

cout << "i = " << i << endl;

for (int i = 1; i <= 5; i++) {

if (i == 3) {

continue; // Skip when i == 3

cout << "i = " << i << endl;


}

return 0;

goto Statement:

Used to jump to a specific label in the program (not recommended for structured
programming).

goto label;
label:
// code to execute
Ex- #include <iostream>
using namespace std;

int main() {
int i = 0;

// A loop with the goto statement to exit early


start: // Label
i++;
cout << "i = " << i << endl;
if (i == 3) {
goto end; // Jump to 'end' label when i equals 3
}
goto start; // Jump back to the start label

end: // Label
cout << "Loop ended!" << endl;

return 0;
}

Functions: Functions in programming are blocks of reusable code that perform a


specific task. They help organize code, improve readability, and reduce
redundancy. Functions take input (parameters), perform operations, and return a
result (optional).

Simple Functions:
 Declaration: Defines the function signature. Example:

int add(int a, int b); // Declaration


 Definition: Provides the actual function logic. Example:

int add(int a, int b) {


return a + b;
}
 Calling Functions: Invoking a function to execute its logic. Example:

int result = add(5, 10); // Calling the add function


Ex-
#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

int main() {
int result = add(5, 10); // Calling the function
cout << "Sum: " << result << endl;
return 0;
}
Passing Arguments:

Pass by Value: Pass by Value is a method of passing arguments to a function


where a copy of the actual argument's value is passed to the function. In this case,
the function operates on the copy, and any changes made to the parameter inside
the function do not affect the original variable outside the function.

How It Works:

 When you pass a variable to a function by value, the function gets a copy of
the variable's value.
 Changes made to the parameter inside the function will not affect the
original variable.

When to Use Pass by Value:

 When you want the function to work with a copy of the data.
 When you don’t need to modify the original variable or when the data being
passed is small (like an integer or a float).

Drawback:

 If the data passed is large (e.g., large arrays or objects), copying the data can
be inefficient, so passing by reference might be preferred in such cases.

Syntax:

void function_name(type parameter) {


// code using the parameter
}

Example 1.

#include <iostream>
using namespace std;

void swapByValue(int x, int y) {


int temp = x;
x = y;
y = temp;
cout << "Inside function (After Swap): x = " << x << ", y = " << y << endl;
}

int main() {
int a = 5, b = 10;

cout << "Before Swap: a = " << a << ", b = " << b << endl;

// Calling the function to swap the values


swapByValue(a, b);

cout << "After Swap (Outside function): a = " << a << ", b = " << b << endl;
return 0;
}
 Example 2:

#include <iostream>

using namespace std;

void updateValue(int x) {

x = 10;

int main() {

int a = 5;

updateValue(a);

cout << "Value of a: " << a << endl; // a will remain 5 (no change)

return 0;

Pass by Reference:

In Pass by Reference, the actual memory address of the variable is passed to the
function, allowing the function to directly modify the original variable. This means
that any changes made to the parameter inside the function will affect the original
variable outside the function.

How It Works:

 When you pass a variable by reference, you're passing the memory address
(or reference) of the variable, not its value.
 Any modifications inside the function will directly affect the original
variable because the function operates on the variable's address.

Syntax:
You can pass a parameter by reference using the & symbol in the function
declaration.

void function_name(type &parameter) {


// code using the parameter
}

Example1: Swapping Two Numbers Using Pass by Reference

#include <iostream>
using namespace std;

void swapByReference(int &x, int &y) {


int temp = x;
x = y;
y = temp;
}

int main() {
int a = 5, b = 10;

cout << "Before Swap: a = " << a << ", b = " << b << endl;

// Calling the function to swap the values


swapByReference(a, b);

cout << "After Swap: a = " << a << ", b = " << b << endl;

return 0;
}

Example2 :

#include <iostream>

using namespace std;

void updateValue(int &x) {


x = 10;

int main() {

int a = 5;

updateValue(a);

cout << "Value of a: " << a << endl; // a will be changed to 10

return 0;

Return Statement:

The return statement is used to return a value from a function.

int add(int a, int b) {


return a + b;
}
Types of Functions:

Inline Functions An inline function is a function that is expanded in place where


it is called, rather than being invoked through the usual function call mechanism.
The idea behind inline functions is to reduce the overhead of function calls,
making the program more efficient, especially for small, frequently used functions.

When you declare a function as inline, the compiler attempts to replace the
function call with the actual code of the function at the point of the call. This can
reduce the function call overhead (e.g., saving the stack, jumping to another part of
the program), but it can also increase the size of the code if overused.

 Example:

#include <iostream>

using namespace std;


inline int square(int x) {

return x * x;

int main() {

int result = square(5); // Function call is replaced with the body of the
function

cout << "Square: " << result << endl;

return 0;

Advantages of Inline Functions:

1. Faster Execution:
o Since there's no overhead of function calls, inline functions can
execute faster, especially for small, frequently called functions.
2. Reduced Function Call Overhead:
o The compiler directly replaces the function call with the function
body, reducing the cost of setting up a function call (like saving the
return address, pushing arguments to the stack, etc.).
3. Efficiency for Small Functions:
o Inline functions are ideal for small functions that are called frequently,
such as accessor functions or simple mathematical operations.

Disadvantages of Inline Functions:

1. Code Size:
o If an inline function is large or used extensively, it can increase the
size of the binary because the function code is inserted at every call
site. This could actually hurt performance due to code bloat.
2. Compiler's Discretion:
oThe inline keyword is a suggestion to the compiler, not a command.
The compiler can choose not to inline a function if it's too complex or
if inlining it doesn't provide a performance benefit.
3. Limited to Small Functions:
o Inline functions are only effective for small functions. Large functions
should not be inlined as they will increase the code size and reduce
performance.

When to Use Inline Functions:

 When the function is small and frequently called (e.g., getter/setter


functions, simple mathematical functions).
 When you want to reduce the overhead of function calls for performance
reasons.

When Not to Use Inline Functions:

 For large functions where inlining would lead to code bloat.


 When debugging: inlining can make debugging difficult, as the code can
become harder to trace.

Default Arguments:

Default arguments are values that are automatically assigned to function


parameters if the caller does not provide those values during the function call. In
other words, if a function is called without a value for a parameter with a default
argument, the default value is used. Example:

#include <iostream>

using namespace std;

void printValue(int x = 5) {

cout << "Value: " << x << endl;

}
int main() {

printValue(); // Default argument will be used

printValue(10); // Provided argument will be used

return 0;

Passing and Returning Structure Variables:

Structures can be passed by value or by reference, and function can return


structures.

struct Point {
int x;
int y;
};

Point createPoint() {
Point p = {1, 2};
return p;
}

#include <iostream>
using namespace std;

struct Point {
int x, y;
};

Point createPoint() {
Point p = {1, 2};
return p;
}

int main() {
Point p1 = createPoint();
cout << "Point coordinates: (" << p1.x << ", " << p1.y << ")" << endl;
return 0;
}

Pointers in C++

A pointer is a variable that stores the memory address of another variable. Rather
than storing data directly, a pointer stores the location of where the data is kept.
Pointers are powerful tools in C++ for directly managing memory and interacting
with dynamically allocated memory, among other tasks.

Basic Concepts:

 Pointer Variable: A variable that holds the memory address of another


variable.
 Dereferencing: Accessing the value stored at the memory address a pointer
is pointing to.
 Address-of Operator (&): Used to get the address of a variable.
 Dereference Operator (*): Used to access the value at the address the
pointer is pointing to.

Pointer Syntax:

type *pointer_name; // Declaring a pointer to a variable of type 'type'

 type: The type of data the pointer will point to (e.g., int, float, etc.)
 *: Indicates that the variable is a pointer.
 pointer_name: The name of the pointer variable.

Example 1: Basic Pointer Usage

#include <iostream>
using namespace std;

int main() {
int a = 10; // A normal integer variable
int *ptr = &a; // Pointer 'ptr' stores the address of 'a'
cout << "Value of a: " << a << endl; // Output: 10
cout << "Address of a: " << &a << endl; // Output: Memory address of 'a'
cout << "Pointer ptr points to address: " << ptr << endl; // Output: Same address
as &a
cout << "Value stored at the address ptr points to: " << *ptr << endl; // Output:
10

return 0;
}

Pointer Operations:

1. Address-of Operator (&):


o Returns the address of a variable.

int a = 5;
int *ptr = &a; // 'ptr' now holds the address of 'a'

2. Dereferencing Operator (*):


o Returns the value at the address the pointer is pointing to.

int a = 5;
int *ptr = &a;
cout << *ptr; // Output: 5

Example 2: Pointers and Arrays:

In C++, arrays and pointers are closely related. An array name is a pointer to the
first element of the array.

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer points to the first element of the array

// Accessing array elements using pointer


cout << "First element: " << *ptr << endl; // Output: 10
cout << "Second element: " << *(ptr + 1) << endl; // Output: 20
cout << "Third element: " << *(ptr + 2) << endl; // Output: 30

return 0;
}

Explanation:

 arr is an array, and ptr is a pointer to the first element of arr.


 ptr can be used to access array elements by incrementing the pointer (ptr + 1,
ptr + 2, etc.).

Pointer to Pointer:

A pointer can store the address of another pointer, known as a pointer to pointer.

#include <iostream>
using namespace std;

int main() {
int a = 10;
int *ptr = &a; // Pointer pointing to 'a'
int **ptr2 = &ptr; // Pointer to pointer

cout << "Value of a: " << a << endl; // Output: 10


cout << "Address of a: " << &a << endl; // Output: Address of 'a'
cout << "Pointer ptr points to address: " << ptr << endl; // Output: Address of 'a'
cout << "Pointer to pointer ptr2 points to address: " << *ptr2 << endl; // Output:
Address of 'a'
cout << "Dereferencing ptr2: " << **ptr2 << endl; // Output: 10 (value of 'a')

return 0;
}

Explanation:

 ptr points to a.
 ptr2 points to ptr, which points to a.
 **ptr2 dereferences ptr2 (gives us ptr), and then *ptr gives us the value of a.

Common Pointer Errors:


1. Dereferencing a Null Pointer:
o A pointer that has not been initialized or assigned to a valid address is
called a "null pointer". Dereferencing a null pointer causes undefined
behavior.

int *ptr = nullptr; // Null pointer


cout << *ptr; // Undefined behavior

2. Dangling Pointer:
o A pointer that points to a memory location that has been deallocated
(i.e., freed) is a dangling pointer. Dereferencing a dangling pointer
can lead to crashes or unexpected behavior.

int *ptr = new int; // Memory allocated


delete ptr; // Memory deallocated
// ptr now points to a freed memory location

You might also like