C++ Syntax Ultimate Reference: Complete Programming Cheatsheet for Beginners & Pros

Introduction to C++ Syntax

C++ is a powerful, general-purpose programming language that extends the C language with object-oriented features. Created by Bjarne Stroustrup in 1985, C++ combines low-level memory manipulation with high-level abstractions, making it ideal for system software, application software, game development, drivers, and performance-critical applications.

Basic Program Structure

Every C++ program includes these fundamental elements:

// This is a comment
/* This is a 
   multi-line comment */

#include <iostream>  // Header inclusion

// Namespace declaration
using namespace std;  // Optional but common

// Function declaration
void myFunction();  // Forward declaration

// Main function - program entry point
int main() {
    // Code statements
    cout << "Hello World!";
    
    // Return statement
    return 0;  // Indicates successful execution
}

// Function definition
void myFunction() {
    // Function body
}

Data Types

Primitive Types

TypeDescriptionSizeExample
boolBoolean1 bytebool isActive = true;
charCharacter1 bytechar grade = 'A';
intInteger4 bytesint count = 42;
floatFloating-point4 bytesfloat price = 10.99f;
doubleDouble precision float8 bytesdouble pi = 3.14159;
voidNo valueUsed in functions, pointers
wchar_tWide character2 or 4 byteswchar_t letter = L'Ω';

Type Modifiers

ModifierEffectExample
shortReduces sizeshort int num = 10;
longIncreases sizelong int bigNum = 10000000L;
signedCan be negative (default)signed int num = -42;
unsignedNon-negative onlyunsigned int positiveNum = 42;
long longExtended size for integerslong long int veryBig = 9223372036854775807LL;

Derived Types

TypeDescriptionExample
ArraysCollection of elementsint numbers[5] = {1, 2, 3, 4, 5};
ReferencesAlias to a variableint& ref = original;
PointersStores memory addressint* ptr = &value;

Variables & Constants

Variable Declaration Syntax

data_type variable_name; // Declaration
data_type variable_name = initial_value; // Initialization
data_type variable1, variable2, variable3; // Multiple variables
auto variable_name = value; // Type deduction (C++11)

Constants

const int MAX_VALUE = 100; // Compile-time constant
constexpr int COMPILED_VAL = MAX_VALUE * 2; // C++11 compile-time expression

// Enumeration constants
enum Color {RED, GREEN, BLUE};
enum class Fruit : int {APPLE = 0, ORANGE, BANANA}; // Scoped enum (C++11)

// Define directive (not recommended for most cases)
#define PI 3.14159

Operators

Arithmetic Operators

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulusa % b
++Incrementa++ or ++a
--Decrementa-- or --a

Relational Operators

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b
<=>Three-way comparison (C++20)a <=> b

Logical Operators

OperatorDescriptionExample
&&Logical ANDa && b
||Logical ORa || b
!Logical NOT!a

Bitwise Operators

OperatorDescriptionExample
&Bitwise ANDa & b
|Bitwise ORa | b
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << b
>>Right shifta >> b

Assignment Operators

OperatorDescriptionExample
=Assigna = b
+=Add and assigna += b
-=Subtract and assigna -= b
*=Multiply and assigna *= b
/=Divide and assigna /= b
%=Modulus and assigna %= b
&=Bitwise AND and assigna &= b
|=Bitwise OR and assigna |= b
^=Bitwise XOR and assigna ^= b
<<=Left shift and assigna <<= b
>>=Right shift and assigna >>= b

Other Operators

OperatorDescriptionExample
sizeofSize of variable/typesizeof(int)
.Member accessobject.member
->Member access via pointerpointer->member
::Scope resolutionClass::member
?:Ternary conditionalcondition ? expr1 : expr2
,Commaexpr1, expr2
.*Pointer to memberobject.*memberPtr
->*Pointer to member via pointerpointer->*memberPtr
newDynamic memory allocationint* p = new int;
deleteDynamic memory deallocationdelete p;
new[]Dynamic array allocationint* arr = new int[10];
delete[]Dynamic array deallocationdelete[] arr;
()Function callfunction()
[]Array subscriptarray[index]

Control Flow

Conditional Statements

// If statement
if (condition) {
    // Code executed if condition is true
}

// If-else statement
if (condition) {
    // Code executed if condition is true
} else {
    // Code executed if condition is false
}

// If-else if-else statement
if (condition1) {
    // Code executed if condition1 is true
} else if (condition2) {
    // Code executed if condition2 is true
} else {
    // Code executed if all conditions are false
}

// Switch statement
switch (expression) {
    case value1:
        // Code executed if expression equals value1
        break;
    case value2:
        // Code executed if expression equals value2
        break;
    default:
        // Code executed if no match is found
        break;
}

// Ternary operator
variable = (condition) ? valueIfTrue : valueIfFalse;

Loops

// For loop
for (initialization; condition; update) {
    // Code executed for each iteration
}

// Range-based for loop (C++11)
for (type variable : collection) {
    // Code executed for each element
}

// While loop
while (condition) {
    // Code executed while condition is true
}

// Do-while loop
do {
    // Code executed at least once and then while condition is true
} while (condition);

// Loop control
break;    // Exit loop
continue; // Skip to next iteration
goto label;  // Jump to labeled statement (discouraged)

Functions

Function Declaration & Definition

// Basic function
return_type function_name(parameter_type1 param1, parameter_type2 param2) {
    // Function body
    return value;  // Return statement (if not void)
}

// Function with default parameters
void function_name(int param1 = default_value) {
    // Function body
}

// Function declaration (prototype)
return_type function_name(parameter_type1, parameter_type2);

// Inline function suggestion
inline int add(int a, int b) {
    return a + b;
}

// Function overloading
void print(int value);
void print(double value);
void print(string value);

Lambda Expressions (C++11)

// Basic lambda
auto lambda = []() { cout << "Hello Lambda"; };

// Lambda with parameters
auto add = [](int a, int b) { return a + b; };

// Lambda with capture list
int x = 10;
auto addX = [x](int a) { return a + x; };  // Capture by value
auto addXRef = [&x](int a) { return a + x; };  // Capture by reference
auto addAll = [=](int a) { return a + x; };  // Capture all by value
auto addAllRef = [&](int a) { return a + x; };  // Capture all by reference

// Lambda with return type
auto divide = [](int a, int b) -> double { return a / (double)b; };

Classes & Objects

Class Definition

class ClassName {
private:
    // Private members (accessible only within the class)
    int privateVariable;
    
protected:
    // Protected members (accessible in this class and derived classes)
    int protectedVariable;
    
public:
    // Public members (accessible from anywhere)
    int publicVariable;
    
    // Constructor
    ClassName(int value) : privateVariable(value) {
        // Constructor body
    }
    
    // Destructor
    ~ClassName() {
        // Destructor body
    }
    
    // Member function
    void memberFunction() {
        // Function body
    }
    
    // Const member function (doesn't modify object state)
    int getValue() const {
        return privateVariable;
    }
    
    // Static member function
    static void staticFunction() {
        // Operates on class, not on objects
    }
};

Creating & Using Objects

// Object creation on stack
ClassName obj1(10);

// Object creation on heap
ClassName* obj2 = new ClassName(20);
delete obj2;  // Don't forget to delete heap objects

// Accessing members
obj1.publicVariable = 30;
obj1.memberFunction();

// Accessing via pointer
obj2->publicVariable = 40;
obj2->memberFunction();

Inheritance

// Base class
class Base {
public:
    void baseFunction() { }
};

// Derived class with public inheritance
class Derived : public Base {
public:
    void derivedFunction() { }
};

// Multiple inheritance
class MultiDerived : public Base1, public Base2 {
    // ...
};

// Virtual inheritance (for diamond problem)
class D : virtual public B {
    // ...
};

Polymorphism

class Base {
public:
    // Virtual function (can be overridden)
    virtual void virtualFunction() {
        // Base implementation
    }
    
    // Pure virtual function (must be overridden in derived classes)
    virtual void pureVirtualFunction() = 0;
};

class Derived : public Base {
public:
    // Override
    void virtualFunction() override {
        // Derived implementation
    }
    
    void pureVirtualFunction() override {
        // Implementation required
    }
};

// Using polymorphism
Base* basePtr = new Derived();
basePtr->virtualFunction();  // Calls Derived implementation
delete basePtr;

Templates

Function Templates

// Function template
template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

// Using the template
int maxInt = max<int>(3, 7);    // Explicit type
double maxDouble = max(3.5, 2.5);  // Type deduction

Class Templates

// Class template
template <typename T, int Size = 10>
class Array {
private:
    T elements[Size];
    
public:
    T& operator[](int index) {
        return elements[index];
    }
    
    int size() const {
        return Size;
    }
};

// Using the template
Array<int, 5> intArray;
Array<string> stringArray;  // Uses default Size=10

Template Specialization

// Primary template
template <typename T>
class MyClass {
public:
    void function() {
        // Generic implementation
    }
};

// Explicit specialization
template <>
class MyClass<int> {
public:
    void function() {
        // Specialized implementation for int
    }
};

Namespaces

// Namespace definition
namespace MyNamespace {
    int value = 5;
    void function() { }
    
    // Nested namespace
    namespace Nested {
        int nestedValue = 10;
    }
}

// Using namespace elements
int x = MyNamespace::value;
MyNamespace::function();
int y = MyNamespace::Nested::nestedValue;

// Namespace alias
namespace MN = MyNamespace;
int z = MN::value;

// Using directive (brings all names into current scope)
using namespace MyNamespace;
int a = value;  // Directly accessible

// Using declaration (brings specific name into current scope)
using MyNamespace::function;
function();  // Directly accessible

Exception Handling

// Try-catch block
try {
    // Code that might throw exceptions
    throw SomeException("Error message");
} catch (const SomeException& e) {
    // Handle specific exception
    cout << e.what();
} catch (const std::exception& e) {
    // Handle standard exceptions
    cout << e.what();
} catch (...) {
    // Handle all other exceptions
    cout << "Unknown exception";
}

// Function with exception specification (deprecated in C++17, removed in C++20)
void function() throw(ExceptionType1, ExceptionType2) {
    // Can throw only ExceptionType1 or ExceptionType2
}

// Noexcept specification (C++11)
void safeFunction() noexcept {
    // Promises not to throw exceptions
}

void conditionalNoexcept() noexcept(condition) {
    // Noexcept depends on condition
}

Standard Library Components

Input/Output Streams

#include <iostream>
using namespace std;

// Output to console
cout << "Hello" << 42 << endl;

// Input from console
int value;
cin >> value;

// File operations
#include <fstream>
ofstream outFile("output.txt");  // Output file stream
outFile << "Writing to file" << endl;
outFile.close();

ifstream inFile("input.txt");    // Input file stream
string line;
getline(inFile, line);
inFile.close();

// String streams
#include <sstream>
stringstream ss;
ss << "Value: " << 42;
string result = ss.str();

Containers

#include <vector>
#include <list>
#include <map>
#include <set>
#include <array>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>

// Vector (dynamic array)
vector<int> vec = {1, 2, 3};
vec.push_back(4);
int third = vec[2];

// List (doubly-linked list)
list<int> lst = {1, 2, 3};
lst.push_back(4);
lst.push_front(0);

// Map (associative array)
map<string, int> scores;
scores["Alice"] = 95;
int aliceScore = scores["Alice"];

// Set (collection of unique values)
set<int> uniqueNums = {3, 1, 4, 1, 5};  // Stores 1, 3, 4, 5

// Array (fixed-size array, C++11)
array<int, 3> arr = {1, 2, 3};
int second = arr[1];

// Unordered map (hash table, C++11)
unordered_map<string, int> hashMap;
hashMap["key"] = 100;

// Unordered set (hash set, C++11)
unordered_set<int> hashSet = {3, 1, 4, 1, 5};  // Stores 1, 3, 4, 5

// Queue (FIFO)
queue<int> q;
q.push(1);
int front = q.front();
q.pop();

// Stack (LIFO)
stack<int> s;
s.push(1);
int top = s.top();
s.pop();

Algorithms

#include <algorithm>
#include <vector>
using namespace std;

vector<int> v = {3, 1, 4, 1, 5, 9};

// Sorting
sort(v.begin(), v.end());  // Sort in ascending order
sort(v.begin(), v.end(), greater<int>());  // Sort in descending order

// Searching
auto it = find(v.begin(), v.end(), 4);  // Find element
bool exists = binary_search(v.begin(), v.end(), 4);  // Binary search (requires sorted range)

// Counting
int count_val = count(v.begin(), v.end(), 1);  // Count occurrences
int count_even = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });  // Count with predicate

// Min/Max
auto min_it = min_element(v.begin(), v.end());
auto max_it = max_element(v.begin(), v.end());
auto [min_it, max_it] = minmax_element(v.begin(), v.end());  // C++17

// Transformations
transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; });  // Double each element

// For_each
for_each(v.begin(), v.end(), [](int x) { cout << x << " "; });  // Process each element

Smart Pointers (C++11)

#include <memory>
using namespace std;

// Unique pointer (exclusive ownership)
unique_ptr<int> uptr = make_unique<int>(42);  // C++14
int value = *uptr;  // Dereference
uptr.reset();  // Release ownership and delete

// Shared pointer (shared ownership)
shared_ptr<int> sptr1 = make_shared<int>(42);
shared_ptr<int> sptr2 = sptr1;  // Both share ownership
int count = sptr1.use_count();  // Reference count

// Weak pointer (non-owning reference to shared object)
weak_ptr<int> wptr = sptr1;
if (auto temp = wptr.lock()) {  // Get shared_ptr if object exists
    // Use temp
}

Modern C++ Features (C++11 and beyond)

C++11 Features

// Auto type deduction
auto i = 42;
auto d = 42.0;

// Range-based for loops
for (auto& item : container) {
    // Process item
}

// Nullptr
int* ptr = nullptr;

// Enum classes
enum class Color { Red, Green, Blue };
Color c = Color::Red;

// Strongly-typed enums
enum class Status : uint8_t { Good, Bad, Unknown };

// Initializer lists
vector<int> v = {1, 2, 3, 4};
int array[] = {1, 2, 3, 4};

// Uniform initialization
class C {
public:
    int x;
    double y;
};
C c{1, 2.0};

// Delegating constructors
class D {
public:
    D(int x) : D(x, 0) {}
    D(int x, int y) : x_(x), y_(y) {}
private:
    int x_, y_;
};

// Move semantics
void move_example(string&& str) {
    string new_str = std::move(str);  // Transfer ownership
}

// Lambda expressions (covered earlier)

// Variadic templates
template<typename... Args>
void print(Args... args) {
    (cout << ... << args) << endl;  // C++17 fold expression
}

C++14 Features

// Generic lambdas
auto generic = [](auto x, auto y) { return x + y; };

// Return type deduction
auto add(int x, int y) { return x + y; }  // Return type is deduced

// Variable templates
template<typename T>
constexpr T pi = T(3.1415926535897932385);
double circumference = 2 * pi<double> * radius;

// Binary literals
int binary = 0b10101010;  // Binary representation

C++17 Features

// Structured bindings
pair<int, string> p = {1, "one"};
auto [num, name] = p;

map<string, int> m = {{"one", 1}, {"two", 2}};
for (const auto& [key, value] : m) {
    cout << key << ": " << value << endl;
}

// if constexpr
template<typename T>
void process(T t) {
    if constexpr (is_integral_v<T>) {
        // Only compiled for integral types
    } else {
        // For other types
    }
}

// Inline variables
inline int global_var = 42;

// std::optional
#include <optional>
optional<int> maybe_value();
if (auto val = maybe_value(); val.has_value()) {
    cout << *val;
}

// std::variant
#include <variant>
variant<int, string> var = "hello";
if (holds_alternative<string>(var)) {
    cout << get<string>(var);
}

// std::any
#include <any>
any a = 42;
if (a.type() == typeid(int)) {
    cout << any_cast<int>(a);
}

C++20 Features

// Concepts
template<typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};

template<Addable T>
T add(T a, T b) {
    return a + b;
}

// Ranges
#include <ranges>
vector<int> v = {1, 2, 3, 4, 5};
auto even = v | views::filter([](int n) { return n % 2 == 0; });

// Three-way comparison (spaceship operator)
struct Point {
    int x;
    int y;
    auto operator<=>(const Point&) const = default;
};

// Modules (support varies by compiler)
// import <iostream>;
// import mymodule;

// Coroutines
#include <coroutine>
#include <optional>

// Feature test macros
#ifdef __cpp_concepts
// Code using concepts
#endif

Common Pitfalls and Best Practices

Memory Management

  • Always delete what you new, delete[] what you new[]
  • Prefer smart pointers (unique_ptr, shared_ptr) over raw pointers
  • Be cautious of memory leaks, especially in exception paths
  • Use containers from the standard library instead of manual memory management when possible
  • Implement the Rule of Three/Five/Zero for classes that manage resources

Performance Considerations

  • Pass large objects by const reference to avoid copying
  • Use move semantics for transferring ownership
  • Consider pass-by-value for small, copyable types
  • Avoid unnecessary memory allocations
  • Preallocate container capacity when size is known
  • Use reserve() on vectors before adding many elements

Code Style

  • Be consistent with naming conventions
  • Use meaningful variable and function names
  • Keep functions small and focused
  • Follow the Single Responsibility Principle
  • Use const whenever possible
  • Prefer auto for complex types or when type is obvious
  • Use nullptr instead of NULL or 0 for pointers

Compatibility

  • Be aware of compiler differences
  • Use feature test macros for new language features
  • Be careful with implementation-defined behavior
  • Specify the C++ standard version in your build system
  • Be mindful of platform-specific code

Resources for Further Learning

Official Documentation

Books

  • “The C++ Programming Language” by Bjarne Stroustrup
  • “Effective C++” by Scott Meyers
  • “C++ Primer” by Stanley Lippman
  • “Modern C++ Design” by Andrei Alexandrescu
  • “A Tour of C++” by Bjarne Stroustrup

Online Resources

Scroll to Top