Fundamentals 66 min read

Unlock 50,000 Words of C/C++ Mastery: Key Concepts, Code & Tips

This comprehensive C/C++ knowledge base covers everything from basic syntax, const, static, and this pointers to advanced topics like inline functions, virtual methods, smart pointers, STL containers, data structures, algorithms, operating system concepts, networking layers, and common interview problems, complete with code examples and diagrams.

Open Source Linux
Open Source Linux
Open Source Linux
Unlock 50,000 Words of C/C++ Mastery: Key Concepts, Code & Tips

C/C++ Knowledge Summary (≈50,000 words)

This article provides an extensive overview of C/C++ concepts, ranging from language fundamentals to advanced topics, data structures, algorithms, operating systems, and networking.

Table of Contents

C/C++

STL

Data Structures

Algorithms

Problems

Operating System

Computer Networks

Const

Purpose

Qualify a variable as immutable.

Qualify pointers (pointer to const vs const pointer).

Const references for parameters to avoid copies and prevent modification.

Qualify member functions to forbid modification of member variables.

Usage

class A {
    private:
        const int a; // const data member, must be initialized in initializer list
    public:
        A();
        A(int x) : a(x) {};
        const int getValue() const; // const member function
};

void function() {
    const A a; // can only call const member functions
    const A* p = &a; // const pointer to const object
    const A& q = a; // const reference
    const char* p2 = "Hello"; // pointer to const char array
    char* const p3 = greeting; // const pointer to mutable char array
    const char* const p4 = greeting; // const pointer to const char array
}

void function1(const int Var); // parameter cannot be modified inside
void function2(const char* Var); // pointer to const data
void function3(char* const Var); // const pointer
void function4(const int& Var); // const reference

const int function5(); // returns a const int
const int* function6(); // returns pointer to const int
int* const function7(); // returns const pointer to int

Static

Purpose

Qualify ordinary variables to give them static storage duration.

Qualify ordinary functions to limit their visibility to the defining file.

Qualify member variables so all objects share a single instance.

Qualify member functions so they can be called without an object instance.

this Pointer

this

is an implicit pointer inside every non‑static member function, pointing to the object on which the function is invoked.

When a member function is called, the compiler passes the object's address as this.

In const member functions, this has type const ClassName* const, meaning the pointed‑to object cannot be modified. this is an r‑value; you cannot take its address.

Common uses include enabling method chaining, preventing self‑assignment, and implementing data structures like linked lists.

inline Functions

Characteristics

Function body is expanded at each call site.

No function call overhead (no stack frame setup).

Provides type checking unlike macros.

Cannot contain loops, recursion, or complex statements like switch.

Member functions defined inside a class are implicitly inline (except virtual functions).

Usage

inline int functionName(int a, int b) { /* ... */ }
class A {
    int doA() { return 0; } // implicitly inline
};
inline int A::doA() { return 0; } // explicit inline

Compiler Handling

Copy the function body to the call site.

Allocate storage for local variables.

Map input parameters and return values to the caller's locals.

If multiple return points exist, transform them into a single exit block (using GOTO).

Pros & Cons

Pros:

Eliminates call overhead, improving speed.

Retains type safety.

Debuggable.

Cons:

Code bloat.

Changes require recompilation of all translation units.

Inlining is a suggestion; the compiler may ignore it.

Virtual Functions and Inline

Virtual functions can be declared inline, but they are only inlined when the compiler can determine the exact class at compile time (no runtime polymorphism).

assert()

assert

is a macro defined in <assert.h> (C) or <cassert> (C++). It aborts program execution if its condition evaluates to false. Defining NDEBUG disables assert, but the macro must be defined before including assert.h.

sizeof()

On arrays, yields total size of the array.

On pointers, yields size of the pointer itself.

#pragma pack(n)

Sets structure, union, and class member alignment to n bytes.

Bit‑fields

Bit mode: 2; // occupies 2 bits

Bit‑fields are useful for compactly transmitting binary data, but their layout is implementation‑dependent.

volatile

volatile int i = 10;

Prevents the compiler from optimizing accesses to the variable.

Ensures each read fetches the current value from memory.

Can be combined with const (e.g., read‑only hardware registers).

Pointers can also be volatile.

extern "C"

Specifies C linkage for functions and variables, preventing C++ name mangling and enabling linking with C libraries.

struct vs class

Both define types; the default access specifier differs (struct defaults to public, class defaults to private).

union

Provides storage sharing among members; only one member can hold a value at a time. Unions cannot contain reference members, cannot be inherited, and cannot have virtual functions.

Memory Allocation and Management

malloc / calloc / realloc / alloca

malloc

: allocates uninitialized memory. calloc: allocates zero‑initialized memory. realloc: changes size of previously allocated block. alloca: allocates on the stack (non‑portable).

free

Frees memory allocated by malloc / calloc / realloc and sets pointer to nullptr after freeing.

new / delete

new

allocates memory and calls constructors. delete calls destructors and frees memory.

Placement new allows constructing an object at a specific address.

Smart Pointers (C++ Standard Library)

shared_ptr

: shared ownership, reference‑counted. unique_ptr: exclusive ownership, movable. weak_ptr: non‑owning reference to a shared_ptr object, helps break reference cycles. auto_ptr: deprecated in C++11.

Explicit Constructors

Mark a constructor explicit to prevent implicit conversions.

class Test2 {
    public:
        explicit Test2(int n) { /* ... */ }
};

Test2 t2(12); // OK
// Test2 t2 = 12; // error: implicit conversion not allowed

Friend Classes and Functions

Can access private members.

Breaks encapsulation.

Not transitive; one‑way relationship.

using Declarations

Introduce a single name from a namespace; preferred over using namespace to avoid polluting the global namespace.

Scope Resolution Operator ::

::name

: global scope. Class::member: class scope. Namespace::name: namespace scope.

enum Types

Scoped enums ( enum class) provide strong typing; unscoped enums are implicit.

decltype

Deduce the type of an expression.

decltype(expression) var = expression;

References

lvalue reference: binds to existing objects.

rvalue reference: binds to temporaries, enables move semantics.

Reference collapsing rules for templates.

Macros

Macro substitution is textual; not type‑checked.

Member Initialization Lists

Initialize members before the constructor body; required for const members, reference members, and types without default constructors.

initializer_list (C++11)

Allows list‑initialization of containers and custom types.

Type Casting Operators

static_cast

: compile‑time, no runtime check. dynamic_cast: runtime check for polymorphic types. const_cast: adds/removes const/volatile. reinterpret_cast: low‑level reinterpretation of bits.

Runtime Type Information (RTTI)

typeid

yields a type_info object describing the dynamic type.

Requires at least one virtual function for polymorphic types.

Effective C++

Key guidelines include treating C++ as a federation of languages, preferring const, initializing objects before use, providing virtual destructors for polymorphic bases, avoiding exceptions from destructors, and using RAII.

Google C++ Style Guide

Provides conventions for naming, formatting, and best practices; see the linked diagram for a visual summary.

STL Overview

Containers

Container

Underlying Structure

Complexities

Ordered?

Duplicates?

array

Array

O(1) random access

No

Yes

vector

Array

O(1) push/pop back, O(n) insert/erase front

No

Yes

list

Doubly linked list

O(1) insert/erase, O(n) random access

No

Yes

deque

Double‑ended queue

O(1) insert/erase at both ends

No

Yes

set

Red‑black tree

O(log n) insert/erase/find

Yes

No

map

Red‑black tree

O(log n) insert/erase/find

Yes

No

Algorithms

Algorithm

Underlying Method

Complexity

Stable?

find

Linear search

O(n)

Yes

sort

Introsort (quick+heap+insertion)

O(n log n)

Yes

Data Structures

Sequential Structures

Examples include sequential stack, queue, list, and array implementations with accompanying C code snippets.

Linked Structures

Implementation of singly, doubly, and circular linked lists, as well as linked queues.

Hash Tables

Discusses hash functions, collision resolution methods (chaining, open addressing), and linear probing data structures.

Recursion

Explains recursion, its relationship with divide‑and‑conquer, and contrasts with iteration.

Generalized Lists

Shows head‑tail linked representation and extended linear representation.

Binary Trees

Properties, storage (array vs pointer), traversals (pre‑order, in‑order, post‑order, level‑order), and classifications (full, complete, BST, AVL, red‑black, B‑tree, B+‑tree, etc.).

Algorithms

Sorting

Algorithm

Average

Worst

Space

Stable

Bubble

O(n²)

O(n²)

O(1)

Yes

Quick

O(n log n)

O(n²)

O(log n)

No

Merge

O(n log n)

O(n log n)

O(n)

Yes

Searching

Algorithm

Average

Space

Condition

Sequential

O(n)

O(1)

Unordered or ordered

Binary

O(log n)

O(1)

Ordered

Graph Search

Algorithm

Data Structure

Time

Space

BFS

Adjacency matrix / list

O(|V|²) / O(|V|+|E|)

O(|V|²) / O(|V|+|E|)

DFS

Adjacency matrix / list

O(|V|²) / O(|V|+|E|)

O(|V|²) / O(|V|+|E|)

Problems

Chessboard Coverage

Knapsack

Neumann Neighbor

Round Robin Scheduling

Oil Pipeline

Operating System Topics

Processes and Threads

In thread‑enabled systems, a process is a resource‑allocation unit while a thread is a scheduling unit. In non‑threaded systems, the process serves both roles.

Inter‑process Communication (IPC)

Pipe (named and unnamed): half‑duplex, limited buffer.

Semaphore: counting mechanism for synchronization.

Signal: asynchronous notification.

Message Queue: kernel‑resident linked list of messages.

Shared Memory: fast, large data exchange; requires explicit synchronization.

Socket: network‑wide communication.

Thread Communication

Mutex, read‑write lock, spinlock, condition variable.

Semaphores (named and unnamed).

Signals, barriers.

Resource Sharing

Process private: address space, heap, globals, stack, registers.

Process shared: code segment, common data, process ID.

Thread private: stack, registers.

Thread shared: heap, address space, globals, static data.

Linux Kernel Synchronization

Atomic operations

Semaphores, rw_semaphore

Spinlocks

Big Kernel Lock (BKL)

rwlock, brlock

RCU (Read‑Copy‑Update)

seqlock

Deadlock

Causes include resource shortage, improper allocation, and unsuitable execution order. Four necessary conditions: mutual exclusion, hold‑and‑wait, no preemption, circular wait. Prevention methods break one of these conditions (e.g., resource ordering, Banker's algorithm).

File Systems

Windows: FCB table + FAT + bitmap.

Unix: inode + mixed indexing + block grouping.

Byte Order

Host byte order (endianness) can be big‑endian or little‑endian; network byte order is big‑endian. Sample code to detect endianness is provided.

Page Replacement Algorithms

Global vs. local replacement.

OPT, FIFO, LRU, Clock, Working‑set, etc.

Computer Networking

OSI Model

Layer

Function

Protocols

Physical

Bit transmission, electrical/mechanical specs

RJ45, Ethernet

Data Link

Frame assembly, point‑to‑point delivery

PPP, HDLC, VLAN, MAC

Network

Packet routing and inter‑networking

IP, ICMP, ARP, OSPF, RIP

Transport

End‑to‑end reliable delivery

TCP, UDP

Session

Session management

NetBIOS, RPC

Presentation

Translation, encryption, compression

JPEG, MPEG

Application

Network services

HTTP, FTP, DNS, SMTP

Physical Layer

Transmission media, simplex/half‑duplex/full‑duplex, multiplexing techniques (FDM, TDM, WDM, CDM).

Data Link Layer

Point‑to‑point and broadcast channels, framing, error detection (CRC), PPP.

Broadcast Communication

Unicast: one‑to‑one.

Broadcast: one‑to‑all.

Multicast: one‑to‑many.

Google C++ Style Guide Diagram
Google C++ Style Guide Diagram

Source: https://github.com/huihut/interview and various referenced articles.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Memory ManagementprogrammingCData StructuresAlgorithmsNetworkingSystemsSTL
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.