0% found this document useful (0 votes)
2 views29 pages

c++ text book

The document provides a comprehensive overview of variables and data types in C++, including their declaration, initialization, and the differences between primitive and derived data types. It explains user-defined data types such as structures, classes, unions, and enumerations, along with their usage and benefits. Additionally, it covers string handling, scope in C++, and the importance of understanding data ranges for effective programming.
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)
2 views29 pages

c++ text book

The document provides a comprehensive overview of variables and data types in C++, including their declaration, initialization, and the differences between primitive and derived data types. It explains user-defined data types such as structures, classes, unions, and enumerations, along with their usage and benefits. Additionally, it covers string handling, scope in C++, and the importance of understanding data ranges for effective programming.
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/ 29

A variable is a named storage location in memory that holds a value.

In C++, variables
must be declared with a specific data type, which determines the kind of data they can
store.

Declaring and Initializing Variables

Syntax: Data_type variable_name = value;

Int age = 25;

Float price = 99.99;

Char grade = ‘A’;

Bool isPassed = true;

Declaration:

Int x; → This tells the compiler to reserve memory for an integer variable x, but it does not
assign any value. The content of x is undefined until explicitly assigned.

Initialization:

X = 10; → This assigns the value 10 to x. If x was previously uninitialized, it now holds a
definite value.

Combined Declaration & Initialization:

Int x = 10; → This both declares x and initializes it with 10 in a single step.

This is the most common way to define variables when an initial value is available.

Declaration: int x; (reserves memory but doesn’t assign a value)

Initialization: x = 10; (assigns a value)

Combined: int x = 10;

Data Types

In C++, data types specify the kind of data a variable can store. Understanding them is
crucial for efficient memory management and program correctness.

1. Primitive Data Types (Built-in Types)

These are the fundamental types provided by C++.

1.1 Integer Types

Integer types store whole numbers and can be signed (default) or unsigned.

Int is the most commonly used integer type and typically occupies 4 bytes of memory.
Short int (or simply short) is a smaller integer type, usually 2 bytes.

Long int (or long) is typically 4 or 8 bytes, depending on the system.

Long long int (or long long) is an extended integer type that usually takes 8 bytes, allowing
for very large numbers.

Unsigned versions (e.g., unsigned int, unsigned long) store only non-negative values,
effectively doubling the maximum positive range.

Int x = -10; // Signed integer

Unsigned int y = 100; // Unsigned integer

Long long z = 9223372036854775807; // Large integer

Floating-Point Types

Floating-point types store numbers with decimal points.

Float is a single-precision floating-point type that typically takes 4 bytes and provides
around 6-7 decimal digits of precision.

Double is a double-precision floating-point type that usually takes 8 bytes and provides
around 15-16 decimal digits of precision.

Long double offers even higher precision and may take 8 to 16 bytes, depending on the
system.

Float pi = 3.14f; // Single precision

Double e = 2.718281828; // Double precision

Long double preciseValue = 3.14159265358979323846L; // High precision

Character Type:

The char data type stores a single character and typically takes 1 byte.

It can represent ASCII characters or other character encodings.

Wchar_t (wide character) is used for Unicode characters and may take 2 or 4 bytes.

Char16_t and char32_t are specialized types used for UTF-16 and UTF-32 encoding,
respectively.

Char letter = ‘A’;

Wchar_t wLetter = L’Ω’; // Wide character

Char16_t utf16Char = u’अ’; // UTF-16 encoded character


Char32_t utf32Char = U’𐍈’; // UTF-32 encoded character

Boolean Type

The bool data type represents true or false values and typically takes 1 byte

Bool isCodingFun = true;

Bool isDarkModeEnabled = false;

Derived Data Types in C++

Derived data types are built using primitive data types. They help manage complex data
structures efficiently and improve code organization. The primary derived data types in
C++ are:

1. Arrays
2. Pointers
3. References
4. Function Pointers

1. Arrays

An array is a collection of elements of the same data type, stored in contiguous memory
locations. Arrays allow multiple values to be stored under a single variable name, making
data management easier.

1.1 Declaration and Initialization

Int arr[5] = {10, 20, 30, 40, 50}; // Declaration and Initialization

If an array is not initialized, it contains garbage values.

1.2 Accessing Elements

Array elements are accessed using an index (zero-based numbering).

Cout << arr[0]; // Outputs 10

Cout << arr[2]; // Outputs 30

1.2 Looping Through an Array

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

Cout << arr[i] << “ “;

1.3 Multi-Dimensional Arrays


C++ supports multi-dimensional arrays, such as 2D arrays, useful for representing
matrices.

Int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

Cout << matrix[1][2]; // Outputs 6

2. Pointers

A pointer is a variable that stores the memory address of another variable. They allow
direct memory access and manipulation, making them crucial for dynamic memory
allocation, arrays, and function calls.

2.1 Pointer Declaration and Initialization :

Int x = 10;

Int* ptr = &x; // ptr stores the address of x

2.2 Dereferencing a Pointer

The dereference operator (*) allows accessing the value stored at a pointer’s address.

Cout << *ptr; // Outputs 10

2.3 Null and Void Pointers

A null pointer does not point to any valid memory location.

Int* ptr = nullptr;

A void pointer is a generic pointer that can store the address of any data type.

Void* ptr;

Int x = 10;

Ptr = &x; // Can store any type of variable

2.3 Pointer Arithmetic

Int arr[3] = {10, 20, 30};

Int* ptr = arr;

Cout << *ptr; // Outputs 10

Ptr++; // Moves to the next memory location

Cout << *ptr; // Outputs 20


3. References

A reference is an alias for an existing variable. Unlike pointers, a reference must be


initialized at the time of declaration and cannot be changed to reference another variable.

3.1 Declaration and Initialization

Int x = 10;

Int& ref = x; // ref is another name for x

Now, ref and x refer to the same memory location.

3.2 Modifying Value Through a Reference

Ref = 20; // Changes x to 20

Cout << x; // Outputs 20

3.3 References in Function Parameters

Using references in functions avoids copying data, improving performance.

Void update(int& num) {

num += 10; // Modifies original value

Int main() {

Int a = 5;

Update(a);

Cout << a; // Outputs 15

4. Function Pointers

A function pointer is a pointer that stores the address of a function, allowing dynamic
function calls.

4.1 Declaring and Assigning Function Pointers


#include <iostream>

Using namespace std;

Void greet() {

Cout << “Hello, World!”;

Int main() {

Void (*funcPtr)(); // Declare a function pointer

funcPtr = greet; // Assign function address

funcPtr(); // Call function using pointer

Function Pointers with Parameters

#include <iostream>

Using namespace std;

Void add(int a, int b) {

Cout << a + b;

Int main() {

Void (*funcPtr)(int, int) = add;

funcPtr(5, 10); // Outputs 15

Conclusion

Derived data types extend the capabilities of primitive types, enabling more complex and
efficient programs.

Arrays store multiple values of the same type.

Pointers store memory addresses, enabling dynamic memory access.

References act as aliases to variables, improving efficiency.

Function pointers store function addresses, allowing dynamic execution.


User-Defined Data Types in C++
User-defined data types allow programmers to create custom structures by grouping
multiple variables of different types, improving code organization and reusability.
A structure (struct) is a collection of related variables of different data types grouped
under a single name. It helps manage complex data efficiently. Structure members are
accessed using the dot (.) operator.

#include <iostream>
Using namespace std;
Struct Student {
Int id;
Char name[50];
Float marks;
};

Int main() {
Student s1 = {101, “John”, 85.5};
Cout << “ID: “ << s1.id << “, Name: “ << s1.name << “, Marks: “ << s1.marks;
}

A class (class) is an advanced structure that supports data encapsulation and object-
oriented programming (OOP). A class contains data members (variables) and member
functions (methods).

#include <iostream>
Using namespace std;

Class Car {
Public:
String brand;
Int year;
Void display() {
Cout << “Brand: “ << brand << “, Year: “ << year;
}
};

Int main() {
Car myCar;
myCar.brand = “Tesla”;
myCar.year = 2022;
myCar.display();
}

A union (union) is similar to a structure, but all members share the same memory
location, meaning only one member can hold a value at a time. This makes unions
memory-efficient but limits simultaneous data storage.
#include <iostream>
Using namespace std;
Union Data {
Int i;
Float f;
};

Int main() {
Data d;
d.i = 10;
cout << “Integer: “ << d.i << endl;
d.f = 3.14; // Overwrites previous value
cout << “Float: “ << d.f << endl;
}

An enumeration (enum) assigns meaningful names to integral constants, making code


more readable. By default, the first enumerator is assigned 0, the second 1, and so on.
We can also manually assign values.

#include <iostream>
Using namespace std;
Enum Status { SUCCESS = 1, FAILURE = -1, PENDING = 0 };

Int main() {
Status currentStatus = SUCCESS;
Cout << currentStatus; // Outputs 1
}

The typedef keyword and using alias allow renaming data types for better readability.
Typedef unsigned int uint;
Uint age = 25;
Cout << age; // Outputs 25
Alternatively, using can be used for type aliasing.
Using uint = unsigned int;
Uint salary = 50000;
Cout << salary;

User-defined data types enhance C++ by providing structured, reusable, and efficient
code. Structures and classes improve data organization, unions optimize memory usage,
enumerations make constants meaningful, and type aliases improve code readability.
Formula to Calculate the Range of Data Types

The range of a data type depends on the number of bits used for storage and whether it is
signed (can store negative values) or unsigned (only positive values).

For Unsigned Data Types

Since all bits are used for magnitude, the range is:
0 to (2ⁿ - 1)
Example: For a 32-bit (4-byte) unsigned int,
0 to (2³² - 1) = 0 to 4,294,967,295

For Signed Data Types

One bit is reserved for the sign, so the range is:


-(2ⁿ⁻¹) to (2ⁿ⁻¹ - 1)
Example: For a 32-bit (4-byte) signed int,
-(2³¹) to (2³¹ - 1) = -2,147,483,648 to 2,147,483,647

Example Calculation for char (1 byte = 8 bits)

Unsigned char: 0 to (2⁸ - 1) = 0 to 255

Signed char: - (2⁷) to (2⁷ - 1) = -128 to 127

To check the range dynamically, you can use the limits library:

#include <iostream>
#include <limits>
Using namespace std;

Int main() {
Cout << “Range of int: “ << numeric_limits<int>::min() << “ to “ <<
numeric_limits<int>::max() << endl;
Cout << “Range of float: “ << numeric_limits<float>::min() << “ to “ <<
numeric_limits<float>::max() << endl;
Cout << “Range of double: “ << numeric_limits<double>::min() << “ to “ <<
numeric_limits<double>::max() << endl;
}
String in C++ vs. String Class (std::string)

In C++, strings can be handled using two approaches:


1. C-style Strings (Character Arrays)
2. C++ std::string Class (from the Standard Library)

C-style Strings (Character Arrays)


A C-style string is a sequence of characters stored in a character array and terminated by
a null character (\0).

Declaring and Using a C-Style String


#include <iostream>
using namespace std;

int main() {
char str[] = "Hello"; // Null-terminated string
cout << str; // Outputs: Hello
}

Key Characteristics of C-style Strings

Stored as an array of characters.


Require a null character (\0) at the end.
Cannot be directly assigned using =.

String functions from <cstring> are used for operations like copying and concatenation.

Example: String Operations Using <cstring>

#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[20] = "Hello";
char str2[] = "World";

strcat(str1, str2); // Concatenates str2 to str1


cout << str1; // Outputs: HelloWorld

cout << strlen(str1); // Outputs: 10 (length of "HelloWorld")


}
C++ std::string Class (String Class in C++)

The std::string class (from <string>) provides a more flexible and safer way to work with
strings.
Declaring and Using a std::string

#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "Hello, World!";
cout << str; // Outputs: Hello, World!
}

Key Features of std::string Class

Supports direct assignment (=) unlike C-style strings.


Allows dynamic resizing (no need to specify a fixed size).
Provides built-in functions like length(), substr(), find(), and append().

Example: String Operations Using std::string

#include <iostream>
#include <string>
using namespace std;

int main() {
string s1 = "Hello";
string s2 = "World";

string s3 = s1 + " " + s2; // Concatenation


cout << s3; // Outputs: Hello World

cout << s3.length(); // Outputs: 11


cout << s3.substr(0, 5); // Outputs: Hello
}

Difference Between C-style Strings and std::string Class


When to Use What?
Use C-style strings when dealing with low-level memory operations or legacy code.
Use std::string class for modern C++ development, as it is safer, easier, and more flexible.
Scope in C++

Scope in C++ defines where a variable or function can be accessed and how long it
remains in memory. Scope determines the lifetime and visibility of variables, ensuring
proper memory management and avoiding conflicts.

1. Local Scope
A local variable is declared inside a function or block ({}) and only exists within that
function or block. It is destroyed when the function/block exits.
Example: Local Variable in a Function

#include <iostream>
Using namespace std;
Void display() {
Int x = 10; // Local variable
Cout << x; // Accessible here
}

Int main() {
Display();
// cout << x; // Error: x is not accessible outside display()
}

Key Points:
X is created when display() is called.
X is destroyed after display() ends.
Cannot be accessed outside display().

2. Global Scope

A global variable is declared outside all functions and can be accessed anywhere in the
program. It exists throughout program execution.

Example: Global Variable


#include <iostream>
Using namespace std;
Int globalVar = 50; // Global variable

Void display() {
Cout << globalVar; // Accessible inside any function
}

Int main() {
Display();
Cout << globalVar; // Also accessible here
}
Key Points:
globalVar is accessible in both display() and main().
Global variables persist throughout the program.
Disadvantage: Can cause naming conflicts and hard-to-debug errors.

3. Block Scope

A block-scoped variable is declared inside {} and exists only within that block. It cannot
be accessed outside the block.

Example: Block Scope

#include <iostream>
Using namespace std;

Int main() {
{
Int num = 42;
Cout << num; // Accessible here
}
// cout << num; // Error: num is not accessible outside the block
}

Key Points:

Num is created when the block {} starts.


Num is destroyed when the block {} ends.
Cannot be accessed outside the block.

4. Function Scope

A function has its own scope, meaning its code cannot be accessed outside its definition.
However, functions can be called from anywhere in the program.

Example: Function Scope

#include <iostream>
Using namespace std;

Void greet() {
Cout << “Hello, World!”;
}

Int main() {
Greet(); // Valid: Calling the function
// cout << greet; // Error: Cannot access function body directly
}
Key Points:
The function greet() can be called anywhere, but its contents are not directly accessible.
A function must be declared before it is used.

5. Class Scope

Class members (variables and functions) belong to a class and can only be accessed
using an object of that class.
Private members can be accessed only inside the class.
Public members can be accessed outside the class.
Example: Class Scope

#include <iostream>
Using namespace std;

Class Car {
Private:
Int speed; // Private (only accessible inside class)
Public:
Void setSpeed(int s) { speed = s; }
Void showSpeed() { cout << speed; }
};

Int main() {
Car myCar;
myCar.setSpeed(100);
myCar.showSpeed(); // Valid
// cout << myCar.speed; // Error: speed is private
}

Key Points:

Speed is private, so it cannot be accessed directly.


setSpeed() and showSpeed() are public and allow indirect access.

6. Namespace Scope

Namespaces group related variables, functions, and classes to avoid naming conflicts.
The std namespace contains standard functions like cout and cin.
Example: Using a Namespace

#include <iostream>
Using namespace std; // Uses standard namespace

Namespace MyNamespace {
Int x = 10;
}

Int main() {
Cout << MyNamespace::x; // Accessing namespace variable
}

Key Points:
Avoids naming conflicts by grouping identifiers.
Must use namespace_name::variable_name to access variables.

7. File Scope (Static Global Variables)

A static global variable is accessible only within the file where it is declared.
Example: File Scope
#include <iostream>
Using namespace std;

Static int fileVar = 20; // Accessible only in this file

Void display() {
Cout << fileVar;
}

Int main() {
Display();
}

Key Points:
Static restricts global variable access to the same file.
Useful for modular programming.
Scope Resolution Operator ::
Used to access global variables, class members, and namespace members when there
is a naming conflict.
Example: Accessing a Global Variable with ::

#include <iostream>
Using namespace std;

Int x = 50; // Global variable

Int main() {
Int x = 10; // Local variable
Cout << x; // Outputs local x (10)
Cout << ::x; // Outputs global x (50)
}

Key Points:
Local and global variables with the same name exist separately.
::x accesses the global variable.

Key Takeaways

1. Local variables exist only inside a function/block and are destroyed after
execution.

2. Global variables exist throughout the program but can lead to conflicts.

3. Class members are private by default, requiring public methods for access.

4. Namespaces help avoid naming conflicts in large programs.

5. Static global variables have file scope, limiting access to the same file.

6. Scope resolution operator :: is used to differentiate between local and global


variables.

Type Casting in C++

Type casting is the process of converting one data type into another. In C++, there are two
types of type casting:
1. Implicit Type Casting (Automatic Conversion)
2. Explicit Type Casting (Manual Conversion)

1. Implicit Type Casting (Automatic Conversion)


Implicit type casting, also called type promotion, happens automatically when a smaller
data type is converted to a larger data type.

Rules of Implicit Conversion:


Lower precision → Higher precision (e.g., int → float)
Smaller size → Larger size (e.g., char → int)
No data loss occurs.

Example: Implicit Type Casting

#include <iostream>
Using namespace std;

Int main() {
Int num = 10;
Double result = num; // Implicit conversion (int → double)
Cout << result; // Outputs: 10.0
}
Key Points:

Num (int) is automatically converted to double.


No need for explicit casting.

2. Explicit Type Casting (Manual Conversion)

Explicit type casting is done manually when converting data types that might lead to data
loss.

Methods of Explicit Type Casting

1. C-Style Casting
2. Function-Based Casting (static_cast, dynamic_cast, reinterpret_cast,
const_cast)
2.1 C-Style Casting (Using Parentheses or type before a value)
This is the traditional method of type conversion.
Example: C-Style Casting

#include <iostream>
Using namespace std;
Int main() {
Double pi = 3.14159;
Int num = (int)pi; // C-style type casting
Cout << num; // Outputs: 3 (decimal part is removed)
}

Key Points:

(int)pi explicitly converts pi to int, removing the decimal part.


Data loss occurs (3.14159 → 3).

2.2 Static Cast (static_cast<type>(value))

The static_cast is the preferred method for type conversion in modern C++. It performs
safe conversions and is more readable.

Example: Using static_cast

#include <iostream>
Using namespace std;

Int main() {
Double pi = 3.14159;
Int num = static_cast<int>(pi); // Explicit conversion
Cout << num; // Outputs: 3
}

Key Points:
Safer than C-style casting.
Only allows compatible conversions (e.g., float to int, int to double).

2.3 Dynamic Cast (dynamic_cast<type>(value))

Used only for pointers and references in polymorphism (inheritance).


Converts a base class pointer to a derived class pointer.
Example: Using dynamic_cast

#include <iostream>
Using namespace std;

Class Base {
Public:
Virtual void show() { cout << “Base class”; }
};

Class Derived : public Base {


Public:
Void show() { cout << “Derived class”; }
};

Int main() {
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe downcasting

If (derivedPtr) {
derivedPtr->show(); // Outputs: Derived class
} else {
Cout << “Type conversion failed!”;
}
}

Key Points:
Used for safe downcasting in inheritance.
Works only with polymorphic classes (must have at least one virtual function).

2.4 Reinterpret Cast (reinterpret_cast<type>(value))

Used for low-level conversions (e.g., converting a pointer of one type to another).
Unsafe and should be used cautiously.
Example: Using reinterpret_cast

#include <iostream>
Using namespace std;

Int main() {
Int num = 65;
Char* ptr = reinterpret_cast<char*>(&num); // Interpret int as char pointer
Cout << *ptr; // May output: ‘A’ (ASCII 65)
}

Key Points:
Converts an integer pointer to a character pointer.
Useful in low-level programming but risky.

2.3 Const Cast (const_cast<type>(value))


Used to remove or add const qualifiers to a variable.

Helpful when dealing with constant variables in functions.


Example: Using const_cast
#include <iostream>
Using namespace std;
Void changeValue(const int* ptr) {
Int* modifiablePtr = const_cast<int*>(ptr); // Removing const
*modifiablePtr = 20;
}

Int main() {
Int num = 10;
changeValue(&num);
cout << num; // Outputs: 20
}

Key Points:
Const_cast removes const, allowing modification.
Use cautiously, as modifying const data can cause undefined behavior.

Summary

1. Implicit Type Casting happens automatically when converting smaller types to


larger types.

2. Explicit Type Casting is needed when converting between incompatible types.

3. C-Style Casting is simple but unsafe; prefer modern C++ casts.

4. Static_cast is safe and should be used for normal conversions.


5. Dynamic_cast is used for safe downcasting in polymorphism.

6. Reinterpret_cast is used for low-level pointer conversions and should be used


carefully.

7. Const_cast removes or adds const to variables and should be used only when
necessary.

Type Modifiers in C++ (const, volatile, auto)

1. Const Modifier (Constant Variables)

The const keyword makes a variable read-only, meaning its value cannot be
modified after initialization.

Example: Using const

#include <iostream>
Using namespace std;

Int main() {
Const int x = 10;
Cout << x << endl;

// x = 20; // Error: Cannot modify a const variable


}

Key Points:

The variable x is declared as const, so any attempt to modify it will cause a


compilation error.

Used for fixed values like PI, configuration settings, and function parameters.

2. Volatile Modifier (Prevents Compiler Optimization)

The volatile keyword tells the compiler not to optimize a variable because its value
may change unexpectedly (e.g., due to hardware events, multithreading, or
system processes).

Example: Using volatile

#include <iostream>
Using namespace std;
Volatile int flag = 0; // Value can change due to external factors

Int main() {
While (flag == 0) {
// Code keeps running until flag is changed
}
Cout << “Flag changed!”;
}

Key Points:

Prevents compiler optimization, ensuring every read operation fetches the latest
value.

Useful in multithreading, hardware programming, and signal handling.

3. Auto Modifier (Type Deduction – C++11+)

The auto keyword allows the compiler to automatically infer the variable type.

Example: Using auto

#include <iostream>
Using namespace std;

Int main() {
Auto x = 10; // Compiler infers int
Auto y = 3.14; // Compiler infers double
Auto text = “Hello”; // Compiler infers const char*

Cout << x << “ “ << y << “ “ << text;


}

Key Points:

Saves time when dealing with complex data types.

Type is determined at compile-time.

Commonly used in iterators and lambda functions.


1. What is a variable in C++?

A variable in C++ is a named storage location in memory that holds a value. Its
value can be changed during the execution of a program.

3. How do you declare and initialize a variable in C++?

Int x; // Declaration
X = 10; // Initialization
Int y = 20; // Declaration and Initialization

4. What are the different ways to initialize a variable in C++?

Copy Initialization: int x = 10;

Direct Initialization: int x(10);

Uniform Initialization (C++11): int x{10};

5. What is the difference between declaration and initialization of a variable?

Declaration: Tells the compiler about the variable’s name and type.

Initialization: Assigns a value to the variable.

6. Primary Data Types in C++

Int: Integer numbers

Float: Single-precision floating point

Double: Double-precision floating point

Char: Single character

Bool: Boolean (true/false)

Void: Represents absence of value

Wchar_t, char16_t, char32_t: Wide character types

7. What is the size of an int in C++?

Typically, 4 bytes (varies by system and compiler).

8. Difference between signed and unsigned integers?


Signed: Can hold positive and negative values.

Unsigned: Can hold only non-negative values, doubling the positive range.

9. Floating-Point Data Types in C++

Float: 4 bytes

Double: 8 bytes

Long double: 12-16 bytes (implementation-dependent)

10. Difference between float, double, and long double?

Float: 32-bit precision

Double: 64-bit precision

Long double: More precision than double

11. What is a char type in C++?

A char stores a single character using 1 byte.

12. How is bool used in C++?

Stores true or false (1 byte).

13. Purpose of wchar_t, char16_t, and char32_t?

Used for wider character encodings like Unicode.

14. What happens if you store a floating-point number in an int?

The decimal part is truncated, losing precision.

15. How do you define an unsigned integer?

Unsigned int x = 100;

16. Maximum value of a long long variable?

Depends on the system, typically 9,223,372,036,854,775,807 (2^63 – 1).

Derived Data Types


17. What is an array in C++?

A collection of elements of the same type stored in contiguous memory.

18. How do you declare and initialize an array?

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

19. What happens if you access an out-of-bounds array index?

Undefined behavior: It can lead to crashes or incorrect values.

20. Loop through an array using a for loop?

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


Cout << arr[i] << “ “;
}

21. What are multi-dimensional arrays?

Arrays with more than one index (e.g., 2D arrays).

Int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};

22. What is a pointer?

A variable that stores the memory address of another variable.

23. Declare and initialize a pointer?

Int x = 10;
Int *ptr = &x;

24. What is pointer dereferencing?

Accessing the value stored at a pointer’s address using *ptr.

25. What is a null pointer?

A pointer that doesn’t point to any memory.

Int *ptr = nullptr;

26. How does pointer arithmetic work?

Ptr++; // Moves to the next memory location


27. What is a reference variable?

An alias for another variable.

Int x = 10;
Int &ref = x;

28. How do references differ from pointers?

References cannot be null.

Must be initialized when declared.

Cannot be reassigned.

29. What is a function pointer?

A pointer that stores the address of a function.

30. How to use function pointers?

Void func() { cout << “Hello”; }


Void (*ptr)() = func;
Ptr();

31. Example of function pointer with parameters?

Int add(int a, int b) { return a + b; }


Int (*ptr)(int, int) = add;
Cout << ptr(3, 4);

User-Defined Data Types

32. What is a structure in C++?

A user-defined data type to group variables.

33. How to define a structure?

Struct Person {
String name;
Int age;
};

34. How are structure members accessed?

Person p;
p.name = “John”;
p.age = 30;

35. What is a class in C++?

A blueprint for creating objects containing data and functions.

36. Difference between class and structure?

Class: Members are private by default.

Struct: Members are public by default.

37. How do you create an object of a class?

Class Car {
Public:
String brand;
};
Car myCar;

38. What is data encapsulation?

Restricting direct access to object data using private members.

39. What is a constructor?

A special function automatically called when an object is created.

40. What is a destructor?

A function called when an object goes out of scope.

41. What is a union in C++?

A memory-efficient data type where all members share the same memory space.

42. How does a union differ from a structure?

Only one member holds a value at a time.

43. What is an enum in C++?

A user-defined type that assigns names to integer values.

44. How are enumeration values assigned by default?


Starting from 0, incrementing by 1.

45. How to explicitly assign values to an enum?

Enum Colors { Red = 1, Blue = 3, Green = 5 };

46. Purpose of typedef and using in C++?

They create type aliases.

Typedef unsigned int uint;


Using uint = unsigned int;

(Continuing with Scope, Type Casting, and String Handling in next sections...)

C++ Interview Questions and Answers (From Question 45)


45. What is the purpose of typedef and using in C++?
Both typedef and using are used to create type aliases, making code more readable and
easier to modify.

Example using typedef (C++98 and later):


Typedef unsigned int uint;
Uint x = 10; // Equivalent to unsigned int x = 10;
Example using using (C++11 and later, preferred for templates):
Using uint = unsigned int;
Uint x = 10;
Scope in C++
47. What is variable scope?
Variable scope defines the region of a program where a variable can be accessed.
48. What is local scope?
Local scope refers to variables declared inside a function or block. They can only be
accessed within that function or block.
49. Give an example of a local variable.
Example:
Void myFunction() {
Int x = 10; // Local variable
Std::cout << x;
}
50. What is global scope?
A variable declared outside all functions has global scope and can be accessed from
anywhere in the program.
51. What is the risk of using global variables?
• They can be modified from anywhere, leading to unexpected behavior.
• They make debugging harder.
• They cause name conflicts in large programs.
52. What is block scope?
Variables declared inside {} are only accessible within that block.
Example:
{
Int a = 5; // Block-scoped variable
}
Std::cout << a; // Error: ‘a’ is out of scope
53. What is function scope?
Variables declared inside a function exist only while the function is running.
54. What is class scope?
Class members have class scope and are accessible using objects of that class.
55. How do access specifiers affect class scope?
• public: Accessible anywhere.
• private: Accessible only inside the class.
• protected: Accessible inside the class and derived classes.
56. What is namespace scope?
A namespace groups related variables and functions to prevent name conflicts.
57. How do you define a namespace?
Example:
Namespace MyNamespace {
Int x = 10;
}
Std::cout << MyNamespace::x;
58. What is the std namespace?
The std namespace contains all the standard library components like cout, cin, string,
etc.
59. How do you use the scope resolution operator ::?
Used to access variables, functions, and classes from a specific scope.
Example:
Std::cout << ‘Hello’;
60. What are static global variables?
A static global variable is limited to the file in which it is declared.
60. How does the static keyword affect variable scope?
• Inside a function: Keeps its value between function calls.
• Inside a class: Shared across all objects of the class.
• At the global level: Limited to the current file.
Arithmetic operators perform basic mathematical operations on numerical values.
Here’s a brief explanation of each:

1. Addition (+)
Used to add two numbers.
Works with integers, floating-point numbers, and characters (ASCII values).
Example:
Int a = 10, b = 5;
Cout << (a + b); // Output: 15

2. Subtraction (-)
Used to subtract one number from another.
Works with integers and floating-point numbers.
Example:
Int a = 10, b = 5;
Cout << (a – b); // Output: 5

3. Multiplication (*)
Used to multiply two numbers.
Example:
Int a = 10, b = 5;
Cout << (a * b); // Output: 50

4. Division (/)
Used to divide one number by another.

If both numbers are integers, the result is an integer (decimal part is ignored).
Example:
Int a = 10, b = 3;
Cout << (a / b); // Output: 3 (not 3.33)
If at least one number is a floating-point type (float or double), the result includes
decimals:
Double x = 10, y = 3;
Cout << (x / y); // Output: 3.33333

5. Modulus (%)
Returns the remainder of integer division.
Works only with integer values.
Example:
Int a = 10, b = 3;
Cout << (a % b); // Output: 1 (remainder of 10/3)

Not valid for floating-point numbers (5.5 % 2.2 is not allowed).

You might also like