B.Sc.
CSIT 2nd C++
Unit 2: Basics of C++ programming
C++ Program Structure, Character Set and Tokens, Data Type, Type Conversion, Preprocessor Directives,
Namespace, Input/Output Streams and Manipulators, Dynamic Memory Allocation with new and delete,
Control Statements.
Functions: Function Overloading, Inline Functions, Default Argument, Pass by Reference, Return by
Reference, Scope and Storage Class.
Pointers: Pointer variables declaration & initialization, Operators in pointers, Pointers and Arrays, Pointer and
Function.
✅ 1. C++ Program Structure
cpp
#include <iostream> // Preprocessor directive
using namespace std; // Namespace
int main() { // Main function
cout << "Hello, World!" << endl; // Output
return 0;
}
✅ 2. Character Set and Tokens
• Character Set: Includes letters, digits, special symbols (+ - * /, etc.), and whitespace.
• Tokens: Smallest elements of a program.
o Keywords: int, return, if, etc.
o Identifiers: User-defined names (main, cout)
o Constants: 5, 3.14, 'A'
o Operators: +, -, =, ==
o Punctuators: ;, {}, ()
✅ 3. Data Types
Built-in Types:
cpp
int a = 10;
float b = 5.5;
char c = 'A';
bool d = true;
Derived/User-defined:
Er. Sital Prasad Mandal 1|Page
B.Sc. CSIT 2nd C++
• Arrays, structures, unions, enums, classes.
✅ 4. Type Conversion
• Implicit (Automatic):
cpp
int a = 10;
float b = a; // a is converted to float automatically
• Explicit (Type Casting):
cpp
float a = 5.5;
int b = (int) a; // a is explicitly cast to int
✅ 5. Preprocessor Directives
• Start with # and are processed before compilation.
cpp
#include <iostream>
#define PI 3.14159
✅ 6. Namespace
• Used to avoid name conflicts.
cpp
namespace MySpace {
int val = 10;
}
int main() {
cout << MySpace::val;
}
✅ 7. Input/Output Streams and Manipulators
cpp
#include <iostream>
#include <iomanip> // for manipulators
using namespace std;
Er. Sital Prasad Mandal 2|Page
B.Sc. CSIT 2nd C++
int main() {
int x = 10;
cout << setw(5) << x; // manipulator sets width
}
• cin, cout for input/output
• setw(), setprecision(), fixed, left, right from <iomanip>
✅ 8. Dynamic Memory Allocation with new and delete
In C++, dynamic memory allocation allows you to allocate memory at runtime using the
new and delete operators. This is useful when the size of memory needed is not known at
compile time or when you want to manage memory explicitly.
cpp
int* ptr = new int; // Allocates memory
*ptr = 5;
delete ptr; // Deallocates memory
int* arr = new int[5]; // Array allocation
delete[] arr; // Array deallocation
✅ 9. Control Statements
Conditional
cpp
if (a > b) { ... }
else if (a == b) { ... }
else { ... }
Loops
cpp
for (int i = 0; i < 5; ++i) { ... }
while (condition) { ... }
do { ... } while (condition);
Jump Statements
cpp
break; continue; return;
Er. Sital Prasad Mandal 3|Page
B.Sc. CSIT 2nd C++
✅ 1. Function Overloading
• Same function name, different parameters.
cpp
void show(int a) {
cout << "Integer: " << a << endl;
}
void show(double b) {
cout << "Double: " << b << endl;
}
✅ 2. Inline Functions
• Suggests the compiler to insert the function code directly where it's called.
cpp
inline int square(int x) {
return x * x;
}
Best for small, frequently called functions. Avoid complex logic.
✅ 3. Default Arguments
• Provide default values for parameters.
cpp
void greet(string name = "RAM") {
cout << "Hello, " << name << endl;
}
Must be specified from right to left.
✅ 4. Pass by Reference
Function gets access to the original variable.
#include <iostream>
using namespace std;
void update(int &x) {
Er. Sital Prasad Mandal 4|Page
B.Sc. CSIT 2nd C++
x += 5;
}
int main() {
int a = 10;
update(a);
cout << a; // Output will be 15
return 0;
}
• int &x means x is a reference to an int variable passed into the function.
• x += 5; increases the value of the original variable by 5.
✅ 5. Return by Reference
• Function returns a reference to a variable (use with caution).
cpp
int& getRef(int &x) {
return x;
}
Avoid returning reference to local variables—they are destroyed after function ends.
Explanation:
• int &x: The parameter x is passed by reference, so the function receives a reference to the
original variable.
• int& getRef(...): The function returns a reference to the original variable, not a copy.
Why Use This?
Returning a reference allows the caller to access or modify the original variable.
#include <iostream>
using namespace std;
int& getRef(int &x) {
return x;
}
int main() {
int a = 10;
getRef(a) = 20; // Modifies 'a' directly through the reference
cout << a; // Output will be 20
return 0;
Er. Sital Prasad Mandal 5|Page
B.Sc. CSIT 2nd C++
In this example, getRef(a) = 20; sets a to 20 because the function returns a reference to a.
✅ 6. Scope and Storage Classes
Scope Types:
• Local – inside functions or blocks
• Global – declared outside all functions
• Function scope – labels used in goto
• Class/namespace scope
Storage Classes:
Storage Class Keyword Scope Lifetime Default Initial Value
Automatic auto Local Within block Garbage
External extern Global Entire program Zero (if global)
Static static Local/Global Entire program Zero (if global)
Register register Local Within block Garbage (stored in CPU register if possible)
cpp
static int count = 0; // Retains value between calls
✅ 1. Pointer Variable Declaration & Initialization
A pointer stores the memory address of another variable.
cpp
int a = 10;
int* p; // Declaration
p = &a; // Initialization with address of 'a'
cout << *p; // Outputs: 10 (dereferencing p gives value at that address)
*p = 20; // Changes value of 'a' to 20
cout << a; // Outputs: 20
✅ 2. Operators in Pointers
• & (Address-of): Gives address of a variable
Er. Sital Prasad Mandal 6|Page
B.Sc. CSIT 2nd C++
• * (Dereference): Accesses the value at a memory address
cpp
cout << "Address of a: " << &a << endl;
cout << "Pointer p: " << p << endl; // Address stored in p
cout << "Value at p: " << *p << endl; // Dereferencing
✅ 3. Pointers and Arrays
Pointers can iterate over arrays using arithmetic.
cpp
int arr[3] = {10, 20, 30};
int* p = arr; // Same as &arr[0]
cout << *p << endl; // 10
cout << *(p + 1) << endl; // 20
Arrays and pointers are closely related in C++, though not the same.
✅ 4. Pointers and Functions
a) Pass by Pointer
cpp
void update(int* p) {
*p = *p + 1;
}
int main() {
int a = 5;
update(&a); // Pass address
cout << a; // 6
}
b) Pointer to Function
You can pass functions as arguments using function pointers.
cpp
void greet() {
cout << "Hello!" << endl;
}
int main() {
Er. Sital Prasad Mandal 7|Page
B.Sc. CSIT 2nd C++
void (*funcPtr)() = greet;
funcPtr(); // Calls greet
}
• Declares a function pointer funcPtr that can point to functions returning void and taking no
parameters.
• Initializes funcPtr with the address of greet.
• Invokes the function through the pointer, so it calls greet().
#include <iostream>
using namespace std;
void greet(int a) {
cout << "Hello!" << a << endl;
}
int main() {
void (*funcPtr)(int) = greet; // Correct pointer type
funcPtr(5); // Output: Hello!5
return 0;
}
---------------------------------------------------------------------------------------------------------------------
Review
1. C++ Program Structure
A C++ program typically consists of:
• Preprocessor Directives: Instructions to the compiler (e.g., #include).
• Namespace: Avoids name conflicts (e.g., using namespace std;).
• Main Function: Entry point of the program (int main()).
• Statements and Blocks: Code inside {} to perform tasks.
2. Character Set and Tokens
• Character Set: Includes letters (A-Z, a-z), digits (0-9), special characters (e.g., @, #), and
whitespace.
• Tokens: Basic units of a program, including:
o Keywords: Reserved words (e.g., int, if).
o Identifiers: User-defined names (e.g., variable names).
o Literals: Constants (e.g., 42, "hello").
o Operators: Symbols (e.g., +, =).
o Punctuators: Braces, parentheses, semicolons, etc.
3. Data Types
C++ supports:
Er. Sital Prasad Mandal 8|Page
B.Sc. CSIT 2nd C++
• Basic Types: int, float, double, char, bool.
• Derived Types: Arrays, pointers, references.
• User-Defined Types: struct, class, enum.
• Modifiers: signed, unsigned, short, long.
4. Type Conversion
• Implicit: Automatic conversion (e.g., int to float during arithmetic).
• Explicit: Using casting (e.g., static_cast<double>(intVar)).
5. Preprocessor Directives
Instructions processed before compilation:
• #include: Includes libraries (e.g., #include <iostream>).
• #define: Defines macros (e.g., #define PI 3.14).
• #ifdef, #endif: Conditional compilation.
6. Namespace
• Groups identifiers to avoid name conflicts.
• Example: std namespace contains cout, cin.
• Usage: using namespace std; or std::cout.
7. Input/Output Streams and Manipulators
• Input: cin for reading data.
• Output: cout for displaying data.
• Manipulators: Format output (e.g., setw, setprecision from <iomanip>).
8. Dynamic Memory Allocation with new and delete
• new: Allocates memory dynamically (e.g., int* ptr = new int;).
• delete: Frees memory (e.g., delete ptr;).
• Arrays: int* arr = new int[10]; delete[] arr;.
9. Control Statements
• Conditional: if, else if, else, switch.
• Loops: for, while, do-while.
• Jump: break, continue, return.
Er. Sital Prasad Mandal 9|Page