Go2X
Go2X

India's leading training and placement platform offering hands-on learning, powered by 200+ IITian and industry experts, connecting students to 1,000+ hiring and referral partners.

Let's Go2X

Stay updated with Go2X

Get course updates, interview tips, and career insights delivered to your inbox.

Contact Us

Address

1st Floor, Plot No 332, Phase IV, Udyog Vihar,
Sector 19, Gurugram, Haryana 122015

Email

support@go2x.live

Phone

+91 94107 10085

Β© 2025 Go2X Private Limited. All rights reserved.

Made with 🧑 and a lot of late nights.

Interview ExperiencesBlogsAbout UsPrivacy PolicyTerms of ServiceRefund Policy

On This Page:

Coding

C/C++ Interview Questions

Crack your C/C++ interview with 38 in-depth questions covering fundamentals, data types, pointers, memory, functions, recursion, exception handling, templates, and the STL - explained in plain English with code examples.

August 30, 2026
45 mins read

I. Beginner Level

1. What is c++ programming?

C++ is a versatile, compiled programming language created by Bjarne Stroustrup as an enhancement of the C language.C++ accommodates various programming approaches, such as:

  • Procedural programming

  • Object-Oriented Programming (OOP)

  • Generic programming

  • Low-level/system programming

C++ was developed focusing on systems programming, embedded systems, resource-limited software, and large-scale applications, prioritizing performance, efficiency, and versatility in its design. Additionally, C++ has proven valuable in various other areas, with significant advantages in creating software infrastructure and working with resource-constrained applications, such as desktop software, video games, and servers (e.g., for e-commerce, web search, or database management.).

2. C++ is single threaded or multithreaded?

C++ enables programming in both single-threaded and multithreaded environments. Every C++ application begins as a single-threaded program with the main thread executing the main() function by default. Nevertheless, C++ provides strong built-in capabilities for multithreading, permitting the creation of multiple execution units to perform tasks simultaneously.

3. What is an escape sequence? Explain some escape sequences.

An escape sequence in C/C++ language is a sequence of characters that doesn't represent itself when used inside string literal or character. It is composed of two or more characters starting with backslash \.

Some examples are given below:-

  • \n (Newline): Moves the cursor down to the next line. It lets you split a single string of text across multiple lines.

  • \t (Horizontal Tab): Inserts a tab space. It helps align text neatly into columns or even spaces.

  • \\ (Backslash): Prints a single literal backslash. Because a single backslash starts an escape sequence, you must type two to show one.

  • \" (Double Quote): Prints a double quotation mark inside a string. This stops the computer from thinking the quote ends the string early.

  • \b (Backspace): Moves the cursor one step backward. It can erase or step over the character immediately before it

4. What is a preprocessor?

A preprocessor is a program that performs text-level operations like conditional compilation, macro expansion, and file inclusion on source code before the compiler sees it.

β€œAll preprocessing directives begin with a # symbol.”

Some Examples of preprocessor:-

cpp
1#include
2#define  

What it does ?

In languages like C and C++, the preprocessor:

  • Expands macros: Replaces macro names with their definitions (e.g., #define PI 3.14159 causes every PI to be replaced by 3.14159).

  • Includes files: Inserts the contents of header files where #include appears, so the compiler sees one combined translation unit.

  • Handles conditional compilation: Includes or excludes code blocks based on conditions (#if, #ifdef, #ifndef, etc.), useful for platform-specific code or debug builds.

  • Removes comments: Strips out comments since they’re only for humans and not needed for compilation.

  • Performs other text substitutions: Such as line control, error generation (#error), and special instructions (#pragma).

The preprocessor works purely on text; it doesn’t understand C syntax, types, or semantics.

5. What is the namespace in c++?

A namespace in C++ is a container used to organize identifiers like variables, functions, and classes. It helps prevent naming conflicts when the same names are used in different parts of a program. Groups related code under a unique name.Prevents collisions between identifiers having the same name. Improves code organization and readability.

What a namespace does:

  • Prevents naming conflicts: Two different libraries can each define a function or class with the same name, as long as they’re in different namespaces.

  • Organizes code by module or domain: Namespaces express logical grouping, e.g. std for the standard library, Qt for Qt framework, or your own Network, Storage, etc.

  • Controls name lookup: The compiler uses namespaces to resolve which identifier you mean when there are multiple candidates.

6. What is std in C++?

The full form of std is standard and it is a namespace. All the identifiers are declared inside the std namespace, in other words, a namespace provides scope to identifiers such as function names, variable names, etc. defined inside it. It is a feature especially available in C++ and is not present in C. The std keyword is used along with the space resolution operator (::) in every printing line and variable declaration.

Example:

cpp
1std::cout<<"Hey, Bro"<<std::endl;

7. Explain HLL and LLL?

HLL(High Level Language)

  • One can easily interpret and combine these languages as compared to the low-level languages.

  • They are very easy to understand.

  • Such languages are programmer-friendly.

  • Debugging is not very difficult.

  • They come with easy maintenance and are thus simple and manageable.

  • One can easily run them on different platforms.

  • They require a compiler/interpreter for translation into machine code.

  • A user can port them from one location to another.

  • Such languages have a low efficiency of memory. So it consumes more memory than the low-level languages.

  • They are very widely used and popular in today’s times.

  • Java, C, C++, Python, etc., are a few examples of high-level languages.

LLL(Low Level Language)

  • They are also called machine-level languages.

  • Machines can easily understand it.

  • High-level languages are very machine-friendly.

  • Debugging them is very difficult.

  • They are not very easy to understand.

  • All the languages come with complex maintenance.

  • They are not portable.

  • These languages depend on machines. Thus, one can run it on various platforms.

  • They always require assemblers for translating instructions.

  • Low-level languages do not have a very wide application in today’s times.

8. Explain literals, identifiers and keywords?

Literals: Literals in programming are fixed values that represent constant data of a particular type and are written directly in the code. It is a constant value and does not require computation or lookup. 42, 3.14, 'A', "Hello", true, and false are some examples.

Common types of literals (by language family)

In C / C++ / Java–like languages:

  • Integer literals: 0, 42, -7, 0xFF (hex), 0b1010 (binary in C++).

  • Floating-point literals: 3.14, 0.5, 2.0e-3.

  • Character literals: 'A', '\n', '\t'.

  • String literals: "Hello, world!", "" (empty string).

  • Boolean literals: true, false.

  • Null pointer / null reference literals: nullptr (C++), null (Java)

Identifiers: The names used to identify variables, functions, arrays, structures, and other user-defined objects are known as identifiers in programming. A program element is uniquely identified by its name, which can be used to refer to it at a later point in the program.

  • Identifiers can contain uppercase and lowercase alphabets (A–Z, a–z), digits (0–9), and the underscore (_).

  • The first character of an identifier must be a letter or an underscore.

  • Identifiers are case-sensitive.

  • Identifiers cannot be keywords in C (such as int, return, if, while etc.).

Keywords: A keyword can be defined as a β€œReserved Word” that has a specific meaning already defined in the library. These reserved words cannot be used as a variable name. These keywords are also case sensitive and must be written in lowercase letters.

Following are the keywords:

autobreakcasechar
constcontinuedefaultdo
doubleelseenumextern
floatforgotoif
intlongregisterreturn
shortsignedsizeofstatic
structswitchtypedefunion
unsignedvoidvolatilewhile

Example:

cpp
1int age= 20;

Int is a keyword

Age is an identifier

20 is a literal

9. Explain initialized and uninitialized data?

Initialized data: refers to variables or memory locations that have been explicitly assigned a known, definite value at the time of declaration or before use. Uninitialized data refers to variables that have been declared but not given a specific known value, meaning they contain whatever arbitrary "garbage" value happens to exist at that memory location.

Examples of initialized data:

  • int x = 10; β€” explicitly initialized to 10

  • char name[] = "Hello"; β€” initialized with a string

  • static int count = 0; β€” static variable with explicit initial value

  • const int MAX = 100; β€” constant with defined value

Uninitialized data: refers to variables that are declared but not set to a definite known value before use. These variables will have some value, but it is unpredictableβ€”it's whatever residual data ("garbage") was previously stored at that memory address.

Examples of uninitialized data:

  • int x; (local variable in C/C++) β€” contains garbage

  • static int count; β€” implicitly zeroed by runtime, stored in BSS

  • int arr[100]; (global array without explicit values) β€” stored in BSS, zeroed at load time.

10. What are Data types and their types?

A data type is a classification that tells a programming language what kind of value a variable can hold, how much memory to allocate for it, and what operations can be performed on it. Every piece of data in a program has a type that determines how the computer interprets and manipulates that value.

Data Types

text
1β”‚
2β”œβ”€β”€ Primitive (Built-in) data types
3β”‚   β”œβ”€β”€ int, short, long, long long        (4 bytes) 2,3,-5,-6
4β”‚   β”œβ”€β”€ float, double, long double     (4 bytes for float and 8 bytes) for double  3.14, -0.78, 3,5435633, 1.5e
5β”‚   β”œβ”€β”€ char β€˜A’, β€˜B’, β€˜x’, β€˜y’                   (1 byte)
6β”‚   β”œβ”€β”€ bool (C++)                            true/false (1 byte)
7β”‚   └── void no value                       (0 byte)
8β”‚
9β”œβ”€β”€ Derived data types
10β”‚   β”œβ”€β”€ Array
11β”‚   β”œβ”€β”€ Pointer
12β”‚   β”œβ”€β”€ Reference (C++)
13β”‚   └── Function
14β”‚
15└── User-Defined data tyeps
16    β”œβ”€β”€ struct
17    β”œβ”€β”€ class (C++)
18    β”œβ”€β”€ union
19    β”œβ”€β”€ enum
20    └── typedef

11. In modulo operator(%), the answer depends on which operands?

In the modulo operator (%), the result's sign is determined by the first operand (the dividend or numerator), rather than the second operand (the divisor or denominator).

Key Rule:

For the expression a % b:

a represents the dividend (first operand, left side)

b denotes the divisor (second operand, right side)

The result's sign corresponds to the sign of a (the dividend).

text
1| Expression | Result | Explanation                               |
2| ---------- | ------ | ----------------------------------------- |
3| 7 % 3      | 1      | Both positive β†’ positive result           |
4| -7 % 3     | -1     | Dividend is negative β†’ result is negative |
5| 7 % -3     | 1      | Dividend is positive β†’ result is positive |
6| -7 % -3    | -1     | Dividend is negative β†’ result is negative |

12. How does the ternary operator work?

The ternary operator provides a concise method for expressing a basic if...else statement. It is referred to as "ternary" because it involves three operands:

condition ? value_if_true : value_if_false

How it functions:

The condition gets assessed.

If the condition is true, the value following ? is returned.

If the condition is false, the value following : is returned.

age >= 18 ? "Adult" : "Minor"

If age>=18 is true then adult will print, otherwise minor will print

13. What are the arrays? Difference between 1D and 2D array.

An array is a set of elements that share the same data type and are stored in adjacent memory locations. Each element can be accessed via an index.

In C++, the indexing of arrays begins at 0.

  • The one-dimensional array basically consists of a list of variables that have the very same data type.

  • On the other hand, a two-dimensional array consists of a list of arrays- that have similar data types.

  • One can access any specified element in an array with the help of the index of that particular element in the array.

1-D array

  • A one-dimensional array stores a single list of various elements having a similar data type.

  • Linear collection of elements

  • It represents multiple data items in the form of a list.

  • It has only one dimension.

  • One can easily receive it in a pointer, an unsized array, or a sized array.

  • Total number of Bytes = The size of array x the size of array variable or datatype.

Example of 1-D array

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5    int a[5] = {10, 20, 30, 40, 50}; // linear array
6
7    cout << a[2];
8
9    return 0;
10}

Output is 30

2-D array

  • A two-dimensional array stores an array of various arrays, or a list of various lists, or an array of various one-dimensional arrays.

  • It represents multiple data items in the form of a table that contains columns and rows.

  • It has a total of two dimensions.

  • The parameters that receive it must define an array’s rightmost dimension.

  • Total number of Bytes = The size of array visible or datatype x the size of second index x the size of the first index.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5    int a[2][3] = {
6        {10, 20, 30},
7        {40, 50, 60}
8    };  // 2-D array
9
10    cout << a[1][2];
11
12    return 0;
13}

Output is 60

II. Intermediate Level

1. How does a c/c++ file run?

Phase 1: The Build-Time Pipeline (Compilation)

Step1. Preprocessing:

  • The Preprocessor scans your text file for lines starting with a hash symbol (#), known as preprocessor directives.

  • It replaces macro names with their defined values (e.g., changing PI to 3.14).

  • Output: An expanded source code file (.i file)

Step 2. Compiling:

  • The actual Compiler takes the clean .i file and evaluates it for syntax correctness and language rule violations.

  • If the code passes validation, the compiler translates the high-level C/C++ logic into lower-level instruction architecture.Output:

  • An assembly language file (.s file), which features hardware-specific

Step 3. Assembling:

  • The Assembler takes the intermediate .s assembly file and converts it entirely into raw binary format

  • .Output: An object file (.o on Linux/macOS, .obj on Windows). This file contains machine code (0s and 1s)

Step 4. Linking:

  • It combines your generated object file with predefined system library files and any other object files in your project.

  • It maps unresolved placeholders to their actual implementations in memory and stitches in basic startup instructions

  • Output: A standalone executable binary file (.exe)

Phase 2: The Runtime Process (Execution)

Once the binary executable is built, you trigger execution by double-clicking it or calling it via a command line (e.g., ./a.out)

Step 1 Loading:

  • The operating system launches a system utility called the Loader.

  • The loader carves out a new isolated memory space (Process) inside your computer's RAM, copying the binary instructions and data from your storage drive directly into that memory segment

Step 2 Startup Initialization:

  • Before your custom logic runs, the hidden startup code provided by the linker fires up.

  • It maps out the environment variables and registers command-line inputs (argc and argv).

Step 3: The main() Entry Point:

  • The CPU redirects its instruction pointer straight to the starting address of your int main() function.

  • The program sequentially steps through your compiled instructions, fetching variables, performing arithmetic, and routing operations until it hits a return statement or finishes execution

2. What is the cyclic property of data types?

3. Types of error in and where all they occur?

An error is a flaw preventing a program from compiling, running, or working correctly.

  • Syntax Errors: Violations of the coding language's grammar rules.

Where they occur: Caught during the compilation phase (e.g., missing semicolons, misspelled keywords).

  • Runtime Errors: Illegal operations executed while the program runs.

Where they occur: During the execution phase (e.g., dividing by zero, trying to access a null pointer, or running out of memory).

  • Logical/Semantic Errors: Flaws where code runs without crashing but yields the wrong output.

Where they occur: Inside the algorithm or business logic written by the programmer

4. Difference between struct, union and enum?

A struct is a user-defined data type that groups variables of different data types under a single name. Each member has its own separate memory location, and all members can be accessed simultaneously.

Key Characteristics:

  • Memory: Total size = sum of all member sizes (plus padding for alignment)

  • Access: All members can be accessed independently at the same time

  • Use Case: When you need to store multiple related pieces of data together

A union is similar to a structure, but all members share the same memory location. Only one member can hold a value at any given time, making it more memory-efficient than a struct.

Key Characteristics:

Memory: Size = size of the largest member (no separate space for each)

Access: Only one member can be used at a time; writing to one overwrites others

Use Case: Memory optimization, type punning, hardware registers, variant types.

cpp
1#include <stdio.h>
2#include <string.h>
3
4struct Student {
5    int id;
6    char name[50];
7    float gpa;
8};
9
10int main() {
11    struct Student s1;
12    s1.id = 101;
13    strcpy(s1.name, "Alice");
14    s1.gpa = 3.8;
15
16    printf("ID: %d, Name: %s, GPA: %.2f\n", s1.id, s1.name, s1.gpa);
17    printf("Size of struct: %lu bytes\n", sizeof(s1));
18    // Output: Size β‰ˆ 4 + 50 + 4 = 58 bytes (plus padding)
19    return 0;
20}

A union is similar to a structure, but all members share the same memory location. Only one member can hold a value at any given time, making it more memory-efficient than a struct.

Key Characteristics:

  • Memory: Size = size of the largest member (no separate space for each)

  • Access: Only one member can be used at a time; writing to one overwrites others

  • Use Case: Memory optimization, type punning, hardware registers, variant types.

cpp
1#include <stdio.h>
2
3union Data {
4    int i;
5    float f;
6    char c;
7};
8
9int main() {
10    union Data d;
11    d.i = 100;
12    printf("Integer: %d\n", d.i);  // Output: 100
13
14    d.f = 3.14;
15    printf("Float: %.2f\n", d.f);  // Output: 3.14
16    printf("Integer now: %d\n", d.i);  // Output: Garbage (overwritten by float)
17
18    printf("Size of union: %lu bytes\n", sizeof(d));
19    // Output: Size = 4 bytes (size of largest member: float or int)
20    return 0;
21}

3. Enumeration (enum)

An enumeration is a user-defined data type that consists of a set of named integer constants. Enums make code more readable by giving meaningful names to integer values.

Key Characteristics:

  • Memory: Typically 4 bytes (size of int), regardless of the number of constants

  • Access: Only one value from the set can be assigned at a time.

  • Use Case: Days of week, status codes, menu options, state machines

cpp
1#include <stdio.h>
2
3enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
4enum Status { OFF = 0, ON = 1, STANDBY = 2 };
5
6int main() {
7    enum Day today = Mon;
8    enum Status device = ON;
9
10    printf("Today: %d\n", today);      // Output: 1 (Mon = 1, Sun = 0)
11    printf("Device: %d\n", device);    // Output: 1
12
13    printf("Size of enum: %lu bytes\n", sizeof(today));
14    // Output: 4 bytes (size of int)
15
16    return 0;
17}

5. Explain the types caste in c++?

In C++, type casting refers to the conversion of a variable or expression from one data type to a different one.

C++ provides two primary forms of casting:

  • Implicit Type Conversion, which is performed automatically by the compiler.

  • Explicit Type Conversion, which is carried out manually by the programmer.

1. Implicit Type Conversion (Automatic): The compiler performs automatic conversion between data types when it is deemed safe.

This typically occurs when transitioning from a smaller data type to a larger one, a process referred to as promotion.

Example: Converting an int to a double.

Risk: While promotion does not result in data loss, converting from a larger type to a smaller type (for instance, from double to int) may lead to the loss of fractional data or precision.

cpp
1int num = 10;
2double data = num; // Automatically converted to 10.0

2. C-Style Casts (Explicit / Traditional)

Inherited from the C language, this method enables you to enforce a conversion using straightforward syntax.

cpp
1Syntax: (type)expression or type(expression)

Risk: It is strongly advised against in contemporary C++. This is a "brute-force" casting technique that can bypass the compiler's safety mechanisms, potentially resulting in unintended bugs or crashes when incompatible types are cast.

cpp
1double pi = 3.14;
2int num = (int)pi; // Forcefully chops off .14, num becomes 3

6. If there is no else block then how far if block will go?

In C++, if there is no else block, the if statement controls only the next statement when {} braces are not used.

cpp
1if (x > 10)
2    cout << "Hello";
3    cout << "World";

only the first statement belongs to if.

7. What are function and storage classes?

  • A function is a segment of code designed to execute a particular task. It promotes code reusability, modularity, and minimizes code duplication.

  • A function is a self-contained block of code that performs a specific task, while a storage class in programming languages like C and C++ defines the scope, lifetime, initial value, and memory location of a variable or function

  • Definition: A named group of statements that run together when you call or invoke the function name

  • .Purpose: Break large programs into small, reusable pieces

  • .Behavior: Can take inputs (parameters) and return an output (result value).

cpp
1return_type function_name(parameters)
2{
3    // statements
4}
5#include <iostream>
6using namespace std;
7
8int add(int a, int b)
9{
10    return a + b;
11}
12
13int main()
14{
15    cout << add(10, 20);
16
17    return 0;
18}

Here, add() is a function that takes two numbers and returns their sum.

Types of Functions:

  • Library/Predefined Functions – already provided by C++

Example: sqrt(), strlen(), sort()

  • User-Defined Functions – created by the programmer

Example: int add(int a, int b)

Storage Classes

  • Storage classes control four core attributes of variables and functions during a program's runtime:

  • A storage class specifies the scope, lifetime, and storage-related properties of a variable or function.

You can access the variable in your code either locally or globally.

In storage class we see four parameters:

  • Scope: Where you can access the variable in your code (local or global).

  • Lifetime: This refers to the duration the variable remains in memory before it is removed.

  • Storage Location: This indicates where the variable is stored in computer memory, which could be in the stack, data segment, or CPU registers.

  • Initial Value: This is the default value assigned to the variable if you do not specify one yourself.

Storage ClassScopeLIfetimeDefault/Initial Value
AutoLocalBlock LevelGarbage value
StaticLocal/GlobalEntire Program0
ExternGlobalEntire Program0
RegisterLocalBlock levelGarbage

What is the function overloading and parameter passing?

Function Overloading:

  • Definition: The practice of utilizing one function name for various definitions that execute comparable tasks based on different inputs.

  • How it works: The compiler evaluates the quantity and data types of the arguments supplied during a function call to determine which specific version of the function to execute.

  • Key rule: A function cannot be overloaded solely by altering its return type; the parameter list must differ.

Example:

int add(int a, int b) handles two integers.

double add(double a, double b) handles two decimals

Parameter Passing:

  • Definition: The process of passing data from the main program into a function's parameters.

  • Pass by Value: A copy of the actual value is passed to the function. Changes made inside the function do not affect the original variable.

  • Pass by Reference: The memory address of the variable is passed to the function. Changes made inside the function modify the original variable.

8. Difference between block scope variable and globe scope variable?

A block scope variable is a variable declared inside a block { }, while a global scope variable is declared outside all functions and blocks.

cpp
1#include <iostream>
2using namespace std;
3
4int x = 100;   // Global variable
5
6int main()
7{
8    int y = 20;   // Block scope variable
9
10    cout << x << endl;
11    cout << y << endl;
12
13    return 0;
14}

9. What is recursion?

Recursion is a method in C++ which calls itself directly or indirectly until a suitable condition is met. In this method, we repeatedly call the function within the same function, and it has a base case and a recursive condition. The recursive condition helps in the repetition of code again and again, and the base case helps in the termination of the condition.

cpp
1return_type function()
2{
3    if (base_condition)
4        return;
5
6    function();   // Recursive call
7}

If there is no base case in the recursive function, the recursive function will continue to repeat continuously.

Recursion can be used in almost every problem, but there are some cases where the recursion is actually helpful. It is generally used when dealing with complex problems and problems that form a hierarchical pattern; it solves the original problem via the smaller subproblems.

Example:

5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120

cpp
1#include <iostream>
2using namespace std;
3
4int factorial(int n)
5{
6    if (n == 0 || n == 1)
7        return 1;              // Base condition
8
9    return n * factorial(n - 1); // Recursive call
10}
11
12int main()
13{
14    cout << factorial(5);
15     return 0;
16}

Output: 120

How it works

cpp
1factorial(5)
2    ↓
35 Γ— factorial(4)
4    ↓
55 Γ— 4 Γ— factorial(3)
6    ↓
75 Γ— 4 Γ— 3 Γ— factorial(2)
8    ↓
95 Γ— 4 Γ— 3 Γ— 2 Γ— factorial(1)
10    ↓
115 Γ— 4 Γ— 3 Γ— 2 Γ— 1
12    ↓
13120

10. What is the pointer and difference between null, void, wild and dangling pointer?

A pointer in programming refers to a variable that holds the memory address of another variable.

cpp
1#include <iostream>
2using namespace std;
3
4int main()
5{
6    int x = 10;
7    int *p = &x;
8
9    cout << x << endl;   // Value of x
10    cout << p << endl;   // Address of x
11    cout << *p << endl;  // Value at that address
12
13    return 0;
14}

Here:

  • &x β†’ address of x

  • p β†’ stores the address of x

  • *p β†’ accesses the value stored at that address

Types of Pointers:

1. Null Pointer

A null pointer is a pointer that does not point to any valid object or function.

In modern C++, use nullptr

cpp
1int *p = nullptr;

2. Void Pointer

A void pointer is a pointer of type void* that can hold the address of an object of any object type.

cpp
1int x = 10;
2
3void *p = &x;

A void* does not itself tell the compiler what type of object it points to.

3. Wild Pointer

A wild pointer is an uninitialized pointer that contains an indeterminate value and does not point to a known valid object.

cpp
1int *p;   // Wild pointer
2
3// *p = 10;   // ❌ Dangerous

4. Dangling Pointer

A dangling pointer is a pointer that refers to an object or memory location whose lifetime has ended.

Example

cpp
1int *p;
2
3{
4    int x = 10;
5    p = &x;
6}
7
8// x no longer exists here.
9// p is now a dangling pointer.
10
11NULL      β†’ Points to nothing
12VOID      β†’ Generic pointer
13WILD      β†’ Never properly initialized
14DANGLING  β†’ Pointed object is already gone

11. What is addressing in the pointer? Difference between call by value and call by reference?

Using pointers involves utilizing a pointer to hold and retrieve the memory address of a variable.

In C++, there are two key operators employed:

& : Address-of operator: provides the address of a variable.

* : Dereference operator: retrieves the value located at the address.

  • Call by Value

In call by value, a copy of the actual argument is passed to the function.

Therefore, changes made inside the function do not affect the original variable.

Example:

cpp
1#include <iostream>
2using namespace std;
3
4void change(int x)
5{
6    x = 100;
7}
8
9int main()
10{
11    int a = 10;
12
13    change(a);
14
15    cout << a;
16
17    return 0;
18}

output : 10

  • Call by Reference

In call by reference, the function parameter refers to the original variable.

Therefore, changes made inside the function affect the original variable.

cpp
1#include <iostream>
2using namespace std;
3
4void change(int &x)
5{
6    x = 100;
7}
8
9int main()
10{
11    int a = 10;
12
13    change(a);
14
15    cout << a;
16
17    return 0;
18}

Output: 100

12. Explain exception handling?

Exception Handling in C++ is a mechanism used to handle runtime errors and abnormal conditions, allowing a program to continue execution smoothly even in the presence of errors.

Handles abnormal conditions that occur during program execution.

Helps maintain program stability by preventing unexpected program termination.

C++ mainly uses three keywords for exception handling:

try β†’ throw β†’ catch

1. try

The try block contains code that may generate an exception.

2. throw

The throw statement is used to generate/raise an exception.

3. catch

The catch block is used to handle the exception.

Basic try-catch Example:

The try block contains code that might throw an exception, while the catch block handles the exception if it occurs.

cpp
1#include <iostream> 
2using namespace std; 
3int main() 
4{ 
5    int n = 10; 
6    int m = 0; 
7
8    try { 
9        if (m == 0) 
10        throw "Division by zero"; 
11        cout << "Answer: " << n / m; 
12
13    } 
14    catch (const char* msg) {
15        cout << "Error: " << msg; 
16
17    } 
18    return 0; 
19
20}

Internal Working of try-catch Block:

When an exception occurs:

  • The runtime executes code inside the try block.

  • If an exception is thrown, the remaining code inside the try block is skipped.

  • The runtime searches for a matching catch block.

  • If found, the exception is handled.

  • If no matching handler is found, terminate() is called.

  • During this process, stack unwinding occurs and local objects are destroyed automatically.

Types of Exceptions:

There are mainly three types of exceptions in C++:

  • Built-in Exceptions

Built-in exceptions involve throwing primitive data types such as int, char, or float. Although simple, built-in exceptions provide limited information about the error.

  • Standard Exceptions

C++ provides a hierarchy of standard exception classes defined in <exception> and <stdexcept>.

Some commonly used standard exceptions are:

runtime_error

logic_error

out_of_range

invalid_argument

overflow_error

All standard exceptions derive from std::exception and provide the what() function.

  • Custom Exceptions

When standard exceptions are insufficient, custom exception classes can be created

13. Explain file handling?

File handling is the method by which we save data or information in a file using a program. In the C programming language, file handling allows us to store all the data from a program into a file. This data can later be retrieved or extracted from these files for use in any program.

Need of File Handling:

There are instances when the output produced by a program after compilation and execution does not meet our intended objectives. In such situations, we may need to examine the program's output multiple times. However, compiling and executing the same program repeatedly can be a cumbersome task for any programmer. This is precisely where file handling proves to be beneficial.

  • Reusability: File handling enables us to retain the information or data generated after executing the program.

  • Saves Time: Certain programs may require extensive input from users. In these cases, file handling facilitates easy access to specific parts of the code using individual commands.

  • Commendable storage capacity: By storing data in files, you can alleviate concerns about managing large amounts of information within any program.

  • Portability: The data contained in any file can be transferred to another file without any loss of information within the computer system. This significantly reduces effort and minimizes the risk of coding errors.

III. Advanced Level

1. What is a function pointer?

Function pointers hold function addresses, allowing direct calls. Declared with an asterisk and function parameters, they enable callbacks and array integrations. This article covers their declaration, use, and the concept of functions as memory-resident entities.

Key Characteristics:

  • Indirect Calling: It allows you to call a function indirectly through the pointer variable.

  • Signature Matching: The declaration must precisely match the function's signature, meaning the return type and parameter types must be identical.

  • No Arithmetic: You cannot perform pointer arithmetic (like incrementing ++ or decrementing --) on function pointers.

2. What is the virtual table (vtable) mechanism in C++? How does dynamic dispatch work?

A virtual table (vtable) is a compiler-generated structure that contains pointers or entries for the virtual functions associated with a class. It plays a crucial role in supporting runtime polymorphism, allowing C++ to call the correct overridden function when a pointer or reference of the base class refers to an object of the derived class.

cpp
1#include <iostream>
2using namespace std;
3
4class Animal {
5public:
6    virtual void sound() {
7        cout << "Animal sound";
8    }
9};
10
11class Dog : public Animal {
12public:
13    void sound() override {
14        cout << "Dog barks";
15    }
16};
17
18int main() {
19    Animal *p = new Dog();
20
21    p->sound();   // Dog barks
22
23    delete p;
24}

How vtable helps:

text
1Animal*
2   β”‚
3   ↓
4 Dog object
5   β”‚
6   ↓
7 vptr ──────────→ Dog vtable
8                       β”‚
9                       ↓
10                  Dog::sound()

Because sound() is declared virtual, C++ uses dynamic dispatch to select Dog::sound() at runtime.

So basically, β€œA vtable is a compiler-generated mechanism used to implement virtual-function dispatch, enabling runtime polymorphism in C++.”

3. How does a c/c++ program get the memory from the OS?

When you run a C or C++ program, it does not directly access physical RAM. Instead, the Operating System (OS) establishes a virtual address space for the process, which maps virtual memory addresses to physical memory segments (pages) behind the scenes.

How a C/C++ Program Obtains Memory from the OS

The interaction between your program and the OS occurs in two main phases:

1. At Program Startup (Static Allocation)

When you execute the binary, the OS kernel's loader reads the executable file (such as ELF on Linux or PE on Windows). The OS allocates a default segment of virtual memory and loads the compiled machine code, global variables, and initialized constants into designated regions. It also configures a default, fixed-size Stack for the main execution thread.

2. During Runtime (Dynamic Allocation)

When your program requires additional memory during execution (for instance, using malloc() in C or new in C++), it depends on the C/C++ Runtime Library (like glibc or msvcrt) to act as an intermediary:

  • The Memory Allocator: The allocator (such as ptmalloc or jemalloc) oversees a pool of pre-allocated memory known as the Heap.

  • System Calls: If the Heap lacks sufficient space to meet your request, the allocator initiates a system call to request more virtual memory pages from the OS kernel.

  • brk() / sbrk(): These functions are used to extend the data segment boundary (the "break" pointer) for smaller allocations.

  • mmap(): This function is utilized to request entirely separate, anonymous memory mappings from the OS for larger data segments.

  • Memory Release: When you invoke free() or delete, the memory is typically returned to the allocator's internal free pool for future use. The allocator may or may not immediately return those pages to the OS using munmap().

text
1      High Memory Addresses (e.g., 0xFFFFFFFF)
2+------------------------------------------+
3|               Kernel Space                |  <-- Reserved for OS operations
4+------------------------------------------+
5|       Command-Line Args & Env Vars       |  <-- e.g., argc, argv[], envp[]
6+------------------------------------------+
7|                                          |
8|                 STACK                    |  <-- Grows DOWNWARD (towards low addresses)
9|                    |                     |      (Local variables, function frames)
10|                    v                     |
11|                                          |
12|              [ Free Space ]              |  <-- Unallocated virtual memory boundary
13|                                          |
14|                    ^                     |
15|                    |                     |
16|                   HEAP                    |  <-- Grows UPWARD (towards high addresses)
17|                                          |      (Dynamic allocation: malloc/new)
18+------------------------------------------+
19|          BSS Segment (Uninitialized)     |  <-- Global/Static variables initialized to zero
20+------------------------------------------+
21|        Data Segment (Initialized)       |  <-- Global/Static variables initialized by user
22+------------------------------------------+
23|          Text Segment (Code Area)       |  <-- Read-only compiled binary instructions
24+------------------------------------------+
25Low Memory Addresses (e.g., 0x00000000)

4. What are the templates in c++?

C++ templates are the foundation of generic programming, acting as a blueprint for creating generic classes or functions. The idea is to pass the data type as a parameter so you don't need to write the same code for different types.

C++ templates use two keywords- β€˜template’ and β€˜typename’. We can replace β€˜typename’ with the keyword β€˜class’, using class and typename interchangeably.

C++ Template Syntax:

template <parameter1, parameter2, parameter3>

How Do C++ Templates Work?

cpp
1#include <iostream>
2using namespace std;
3
4// Template function to find maximum of two numbers
5template <typename T>
6T findMax(T a, T b) {
7    return (a > b) ? a : b;
8}
9
10int main() {
11    cout << "Max of 3 and 7: " << findMax(3, 7) << endl;
12    cout << "Max of 5.5 and 2.2: " << findMax(5.5, 2.2) << endl;
13    cout << "Max of 'A' and 'Z': " << findMax('A', 'Z') << endl;
14
15    return 0;
16}

Output:

Max of 3 and 7: 7

Max of 5.5 and 2.2: 5.5

Max of 'A' and 'Z': Z

Types of Templates in C++

We use templates in C++ to define generic classes or functions. There are two types of C++ templates:

  • Function Templates

  • Class Templates

A function template in C++ is used to create a single function that can work with different data types. For example, min(), max(), and printArray(). We can also use function overloading to work with multiple data types, but C++ function templates are more powerful when it comes to writing one code that can work with all data types.

cpp
1template <typename T>
2T functionName(T parameter1, T parameter2, ...) {
3    // code
4
5}

2. Class Templates in C++

Similar to function templates, C++ class templates can also be used to create a single class that works with different data types. They are useful when we want to make the code shorter and more manageable.

cpp
1template <class T> class class-name
2{
3   // class body
4}

5. What is STL?

In C++, the Standard Template Library (STL) offers a collection of programming tools designed for implementing algorithms and data structures such as vectors, lists, queues, and more.

The STL utilizes general-purpose classes and functions to implement these data structures and algorithms, all of which have undergone extensive testing.

The C++ STL consists of three primary components:

  • Containers

  • Iterators

  • Algorithms

Containers:

Containers serve as data structures designed to hold objects and data based on specific requirements. Each container is implemented as a template class that includes methods for performing fundamental operations. Every STL container is defined within its own header file.

Containers can be categorized into four types:

  • Sequence Containers: Vector, Deque, List, Forward List, Array

  • Container Adaptors: Stack, Queue, Priority Queue

  • Associative Containers: Set, Multiset, Map, Multimap

  • Unordered Associative Containers: Unordered Set, Unordered Multiset, Unordered Map, Unordered Multimap

Algorithms:

STL algorithms provide a comprehensive array of functions to execute common operations on data (primarily within containers). These functions implement the most efficient versions of algorithms for tasks like sorting, searching, modifying, and manipulating data in containers, among others. Most STL algorithms are defined in <algorithm> and <numeric>, while some specialized algorithms and utilities can be found in other headers such as <memory>, <functional>, and <iterator>. Some of the most commonly utilized algorithms include:

  • Sort: Organizes elements in ascending order (by default).

  • Binary Search: Determines if a value exists within a sorted range.

  • Find: Locates the first occurrence of a specified value.

  • Count: Tallies how many times a value appears within the specified range.

  • Reverse: Inverts the order of elements in the specified range.

  • Accumulate: Calculates the total of all elements in the range.

  • Unique: Eliminates consecutive duplicate elements.

  • Lower bound: Provides an iterator to the first element β‰₯ value in a sorted range.

  • Upper bound: Provides an iterator to the first element > value in a sorted range.

  • Replace: Substitutes all instances of an old value with a new value in the specified range.

Iterators:

Iterators are the pointer like objects that are used to point to the memory addresses of STL containers. They are one of the most important components that contributes the most in connecting the STL algorithms with the containers. Iterators are defined inside the <iterator> header file.

Benefits of C++ Standard Template Library (STL)

  • Reliable and Tested

  • Fast and Efficient

  • Reusability

  • Built-in Algorithms

6. Difference between arrays and vectors?

The main distinction between an array and a vector lies in the fact that an array has a predetermined size that remains constant after it is initialized, while a vector is a dynamic array capable of expanding or contracting automatically as elements are added or deleted.

FeatureArray (std::array / C-Array)Vector (std::vector)
SizeFixed at compile-time.Dynamic at run-time.
Memory AllocationTypically allocated on the Stack.Allocated on the Heap.
Resizing OverheadNo overhead (cannot be resized).Reallocates and copies data when expanded.
Memory EfficiencyHighly efficient; no extra metadata.Higher footprint due to size and capacity tracking.
FunctionsMinimal built-in helper functions.Rich set of methods (push_back, pop_back, etc.).

7. Is it possible to declare an Array without specifying its size?

Yes, but only in certain situations. In C++, an array's size can be deduced automatically when it is initialized at the time of declaration.

1. Size can be omitted during initialization

cpp
1int arr[] = {10, 20, 30, 40, 50};

The compiler automatically determines the size:

Size = 5

2. Size cannot simply be omitted without initialization

cpp
1int arr[];

8. Why are arrays stored in contiguous memory?

Arrays are stored in contiguous memory locations because this allows the elements to be accessed quickly and efficiently using an index.

cpp
1int arr[5] = {10, 20, 30, 40, 50};

Address Value

text
11000           10   ← arr[0]
21004           20   ← arr[1]
31008           30   ← arr[2]
41012           40   ← arr[3]
51016           50   ← arr[4]

Main Reasons

  • Fast random access β€” any element can be accessed directly using its index.

  • Simple address calculation β€” address = base address + offset.

  • Efficient memory management β€” the array occupies one continuous block of memory.

  • Better cache performance β€” nearby elements are stored close together, which often improves CPU cache utilization.

9. Why do arrays use 0-based indexing?

Arrays utilize 0-based indexing mainly because the index signifies a memory offset instead of a count of elements. When programming languages such as C were created, this decision offered direct mathematical and computational advantages that became the norm in the industry.

1. Pointer Arithmetic and Memory Offsets

In a computer's memory, an array is represented as a continuous block of data. The array's variable name directly points to the initial memory location, referred to as the base address. To access any element, the CPU determines its precise location using the following formula:

\(\text{Target\ Address}=\text{Base\ Address}+ (\text{Index}\times \text{Element\ Size})\)

  • With 0-based indexing: To locate the very first element, the calculation is Base Address + (0 Γ— Size) = Base Address. The computer can directly reach the correct location without any additional steps.

  • With 1-based indexing: To find the first element, the formula would need to be modified to Base Address + ((Index - 1) Γ— Size).

So arr[0] naturally refers to the first element.

For example, if the base address is 1000 and an int takes 4 bytes:

text
1arr[0] β†’ 1000 + (0 Γ— 4) = 1000
2arr[1] β†’ 1000 + (1 Γ— 4) = 1004
3arr[2] β†’ 1000 + (2 Γ— 4) = 1008

10. Difference between new and delete operator in c++?

The new operator is used to allocate memory to a variable, arrays, objects, etc. If a large amount of memory is available on the heap, the memory will be initialized by the new operator, and And will return the address of that memory. The use of pointers can store that memory address.

Syntax for the new operator

cpp
1<dataType pointerName> = new <dataType>

Ex: int * p = new int;

We can also initialize value.

Ex: int * p = new int(7);

Example:

cpp
1#include <bits/stdc++.h>
2using namespace std;
3int main() {
4
5  // pointer initialized
6  int * N = new int(5);
7
8  //value printed
9  cout << * N<< endl;
10}

Output: 5

The C++ delete operator is used to deallocate memory that was previously allocated using the new operator. When dynamically allocated memory is no longer needed, the delete operator frees up the memory so that it can be reused by other parts of the program or by the operating system. This helps prevent memory leaks and ensures efficient memory usage in C++ programs

Syntax for delete operator

delete pointerVariable

Example:

cpp
1#include <bits/stdc++.h>
2using namespace std;
3int main() {
4
5  // pointer initialized
6  int * Ninjas = new int(5);
7
8  //value printed
9  cout << * Ninjas << endl;
10
11  //pointer deleted
12  delete Ninjas;
13}

Output :5

Aspectnew Operatordelete Operator
PurposeAllocates memory on the heap for a new object or array.Deallocates memory allocated by the new operator.
Syntaxpointer_variable = new data_type;delete pointer_variable;
Exampleint *ptr = new int;delete ptr;
Memory LeakCan lead to memory leaks if not paired with delete.Proper use prevents memory leaks by freeing memory.
Array AllocationSupports dynamic array allocation with new[].Used with delete[] to deallocate dynamic arrays.
Exception SafetyMay throw std::bad_alloc on failure.Does not throw exceptions.
Custom AllocatorSupports custom memory allocators.Does not support custom memory deallocation strategies.

11. Difference between ordered map and unordered map in c++?

Both map and unordered_map are STL associative containers used to store data in key-value pairs.

mapunordered_map
It stores key-value pairs in sorted order based on the key.It is also storing key-value pairs but not in any specific order
It is implemented using red-black tree.It is implemented using hash table.
It is slower for most operations due to sorting.It is faster for most operations.
It takes O(log n) time for inserting, accessing, and deleting an element.It takes O(1) average time for inserting, accessing, and deleting an element.

Ordered map example:

cpp
1map<int, string> m;
2
3m[3] = "C";
4m[1] = "A";
5m[2] = "B";

Ordered map:

1 A

2 B

3 C

cpp
1unordered_map<int, string> m;
2
3m[3] = "C";
4m[1] = "A";
5m[2] = "B";

The iteration order is not guaranteed to be sorted.

map

  • Sorted

  • Tree

  • O(log n)

unordered_map

  • No guaranteed order

  • Hash Table

  • O(1) Average

12. Compare vector, list and map?

1. Vector

Think of a vector as a series of lockers arranged in a straight line. Since they are stored sequentially in memory, your computer can quickly access any locker if you know its index number.

Best for: Scenarios where you frequently need to read or update elements using an index, or when you primarily add elements to the end of the collection.

The Downside: If you wish to insert or delete an element from the middle of a vector, every element that follows it must shift over to create space or fill the gap, which can be slow for large collections.

2. List

Consider a list as a scavenger hunt. Each element (node) holds the actual data and a pointer ("clue") that leads you to the next element's location in memory.

Best for: Regular insertions or deletions at any point in the collection. You only need to adjust the pointers without moving any other data.

The Downside: You cannot directly access the 50th element; you must start from the first element and follow 50 pointers to reach it.

3. Map

Visualize a map as a real-world dictionary or phone book. Instead of retrieving data by a position number, you access it using a unique identifier, such as a username, product ID, or word.

Best for: Quick lookups based on a specific label. For instance, retrieving a user's profile data using their user_id.

The Downside: Maps require more memory since they must store both the keys and the structural data necessary for organizing the elements for efficient searching.

Found this helpful?

Share it with your network

Related Articles

Frontend

React JS

Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.

Frontend

JavaScript

Prepare for your next tech interview with the most asked JavaScript interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.