DEV Community

Cover image for C++ Code Snippets :)
Madhav Ganesan
Madhav Ganesan

Posted on • Updated on • Originally published at madhavganesan.hashnode.dev

C++ Code Snippets :)

Datatypes



#include <iostream>
using namespace std;

enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

struct Person {
    string name;
    int age;
};

class Rectangle {
private:
    int width, height;

public:
    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }

    int area() {
        return width * height;
    }
};

int main() {
    //Primitive Datatypes
    char c = 'A';        // Character
    int num = 100;       // Integer
    short s = 10;        // Short Integer
    float f = 5.5f;      // Floating point
    double d = 10.99;    // Double precision floating 
    long l = 1234567890; // Long Integer
    bool b = true;       // Boolean

    //Derived Datatypes
    int arr[5] = {1, 2, 3, 4, 5}; // Array
    int *ptr = &num; // Pointer to an integer

    //Enumeration
    Day today = Wednesday;

    //User defined datatyeps
    //struct
    Person person;
    person.name = "Alice";
    person.age = 30;

    //class
    Rectangle rect;
    rect.setDimensions(5, 10);

    return 0;
}


Enter fullscreen mode Exit fullscreen mode


#include <cstdio>

int main() {
    int a;
    long b;
    char c;
    float d;
    double e;

    // Read input values using scanf
    scanf("%d %ld %c %f %lf", &a, &b, &c, &d, &e);

    // Print values using printf
    printf("%d\n", a);
    printf("%ld\n", b);
    printf("%c\n", c);
    printf("%f\n", d);
    printf("%lf\n", e);

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Initialization



#include <iostream>
using namespace std;

int main() {
    int num;
    int num1=0;
    cout<<num; //returns 0
    cout<<num1; //returns 0
}


Enter fullscreen mode Exit fullscreen mode

Basic Input/Output



#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "You entered: " << num << endl;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Command-line arguments



#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
    cout << "Number of arguments: " << argc << endl;

    for (int i = 0; i < argc; i++) {
        cout << "Argument " << i << ": " << argv[i] <<endl;
    }

    return 0;
}


Enter fullscreen mode Exit fullscreen mode


g++ example.cpp -o example
./example arg1 arg2 arg3


Enter fullscreen mode Exit fullscreen mode

For Loop



#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; ++i) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

While Loop



#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 10) {
        cout << i << " ";
        ++i;
    }
    cout << endl;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Functions



#include <iostream>
using namespace std;

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

int main() {
    int result = add(5, 3);
    cout << "Sum: " << result << endl;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Pass by reference:



#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
};

//num - int datatype
//Day - enum
//Person - struct
//array - int* arr - for array, we use pointers reference

void increment(int &num, Day &day, Person &person, int* arr) {
    num++;
}

int main(){
return 0;
}


Enter fullscreen mode Exit fullscreen mode

Storage Classes

auto

It allows the compiler to automatically deduce the type of a variable from its initializer



int main() {
    map<string, int> ages;

    for (auto it = ages.begin(); it != ages.end(); ++it) {
        cout << it->first << ": " << it->second << endl;
    }

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

static

  1. Static Variables Inside Functions A static variable inside a function retains its value between function calls. It is initialized only once, and its lifetime extends across the entire program run. ```cpp

include

using namespace std;

void increment() {
static int count = 0; // Static variable
count++;
cout << "Count: " << count << endl;
}

int main() {
increment(); // Count: 1
increment(); // Count: 2
increment(); // Count: 3
return 0;
}

2. Static Variables Inside Classes
static is used to declare static member variables, which are shared among all instances of the class and can be called using the class name.
```cpp


#include <iostream>

class MyClass {
public:
    static int staticVar; // Declaration of static member variable
    static void staticFunc() { // Declaration of static member function
        std::cout << "Static function called\n";
    }
};

// Definition of static member variable
int MyClass::staticVar = 0;

int main() {
    // Accessing static member variable
    MyClass::staticVar = 5;
    std::cout << "Static variable value: " << MyClass::staticVar << std::endl;

    // Calling static member function
    MyClass::staticFunc();

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

register

Suggests to the compiler to store the variable in a CPU register for faster access. However, it’s only a suggestion and does not guarantee that the variable will be stored in a register.

extern

It is used to declare a variable defined in another file or scope. This allows multiple files to access the same variable.



extern int globalVar; 


Enter fullscreen mode Exit fullscreen mode

const

The const keyword in C++ is used to declare constants or to specify that something is read-only and cannot be modified. When used with a variable, it indicates that the variable's value cannot be changed after initialization.



const int SIZE = 10; // SIZE is a constant with value 10


Enter fullscreen mode Exit fullscreen mode

Classes and Objects



#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}

    int area() const {
        return width * height;
    }
};

int main() {
    Rectangle rect(5, 3);
    cout << "Area: " << rect.area() << endl;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Types of classes

Basic Class:



class BasicClass {
public:
    int data;
    void display() {
        std::cout << "Data: " << data << std::endl;
    }
};


Enter fullscreen mode Exit fullscreen mode

Abstract Class: A class that contains at least one pure virtual function. It cannot be instantiated directly and is typically used as a base class for other derived classes.



class AbstractClass {
public:
    virtual void pureVirtualFunction() = 0;  // Pure virtual function
};


Enter fullscreen mode Exit fullscreen mode

Derived Class: A class that inherits properties and behaviors from a base class



class BaseClass {
public:
    void baseFunction() {
        std::cout << "Base function" << std::endl;
    }
};

class DerivedClass : public BaseClass {
public:
    void derivedFunction() {
        std::cout << "Derived function" << std::endl;
    }
};


Enter fullscreen mode Exit fullscreen mode

Friend Class: A class that is granted access to the private and protected members of another class.



class FriendClass;

class BaseClass {
private:
    int secretData;
    friend class FriendClass;  // Friend class declaration
};

class FriendClass {
public:
    void accessSecret(BaseClass& obj) {
        std::cout << "Secret Data: " << obj.secretData << std::endl;
    }
};


Enter fullscreen mode Exit fullscreen mode

Singleton class:
A singleton class ensures that only one instance of the class exists throughout the lifetime of the application. This is useful when exactly one object is needed to coordinate actions across the system, such as logger, a configuration manager, or a database connection.



#include <iostream>

class Singleton {
private:
    // Private constructor to prevent instantiation
    Singleton() {
        std::cout << "Singleton instance created" << std::endl;
    }

    // Deleted copy constructor and assignment operator to prevent copying
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

public:
    // Static method to provide access to the single instance
    static Singleton& getInstance() {
        static Singleton instance; // Guaranteed to be destroyed and instantiated on first use
        return instance;
    }

    void showMessage() {
        std::cout << "Hello from Singleton" << std::endl;
    }
};

int main() {
    // Access the singleton instance and call a method
    Singleton& singleton = Singleton::getInstance();
    singleton.showMessage();

    // Uncommenting the following lines will cause compilation errors
    // Singleton anotherInstance = Singleton::getInstance(); // Copy constructor is deleted
    // Singleton anotherInstance; // Constructor is private
    // Singleton* ptr = new Singleton(); // Constructor is private

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Anonymous Class
In C++, there is no direct support for anonymous classes (classes without a name)



#include <iostream>

int main() {
    // Define and instantiate an unnamed class
    struct {
        void showMessage() {
            std::cout << "Hello from an unnamed class";
        }
    } anonymousClassInstance;

    // Call the method
    anonymousClassInstance.showMessage();

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Destructor

A destructor in C++ is a special member function that is executed when an object goes out of scope or is explicitly deleted. The main purpose of a destructor is to release resources that the object may have acquired during its lifetime



#include <iostream>

class SimpleClass {
public:
    // Constructor
    SimpleClass() {
        std::cout << "Constructor: Object created" << std::endl;
    }

    // Destructor
    ~SimpleClass() {
        std::cout << "Destructor: Object destroyed" << std::endl;
    }
};

int main() {
    std::cout << "Entering main function" << std::endl;
    {
        SimpleClass obj; // Constructor is called here
    } // Destructor is called here when obj goes out of scope
    std::cout << "Exiting main function" << std::endl;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Memory Allocation

malloc

It allocates a specified amount of memory but does not initialize it. The memory may contain garbage values.



int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
    // Handle allocation failure
}


Enter fullscreen mode Exit fullscreen mode

calloc

It allocates memory for an array of elements and initializes all bytes to zero.



int *arr = (int *)calloc(5, sizeof(int));
if (arr == NULL) {
    // Handle allocation failure
}


Enter fullscreen mode Exit fullscreen mode

realloc

It resizes a previously allocated block of memory. It can either increase or decrease the size and can move the memory to a new location if necessary.



int *arr = (int *)realloc(arr, 10 * sizeof(int));
if (arr == NULL) {
    // Handle reallocation failure, original arr still valid
}


Enter fullscreen mode Exit fullscreen mode

Macros

constants



#define PI 3.14159


Enter fullscreen mode Exit fullscreen mode

functions



#define SQUARE(x) ((x) * (x))


Enter fullscreen mode Exit fullscreen mode

Virtual function

A virtual function is a member function in a base class that you expect to override in derived classes. When you use a virtual function, it ensures that the function call is resolved at runtime based on the actual object type



#include <iostream>

class Base {
public:
    virtual void show() {
        std::cout << "Base class show function" << std::endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        std::cout << "Derived class show function" << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived(); // Base class pointer to Derived class object
    basePtr->show();              // Calls Derived class show function
    delete basePtr;               // Correctly calls Derived and Base destructors
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Inheritance



#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() const {
        cout << "Drawing a shape" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() const override {
        cout << "Drawing a circle" << endl;
    }
};

int main() {
    Shape* shape = new Circle();
    shape->draw();
    delete shape;
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Standard Library Containers

Vector



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

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};
    vec.push_back(6);

    for (int num : vec) {
        cout << num << " ";
    }
    sort(vec.begin(), vec.end());
    cout << endl;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Priority Queue



#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main() {
    priority_queue<int> pq;

    // Insert elements
    pq.push(10);
    pq.push(30);
    pq.push(20);
    pq.push(5);
    pq.push(1);

    // Remove elements
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Map

It is typically implemented using a balanced binary search tree, often an AVL tree (Adelson-Velsky and Landis tree) or a Red-Black tree. Operations like insertion, deletion, and search are performed in O(log N) time complexity.

A collision occurs when two or more keys hash to the same index in the hash table.



#include <iostream>
#include <map>
#include <string>

using namespace std;

void printMap(const map<string, int>& m) {
    for (const auto& pair : m) {
        cout << pair.first << ": " << pair.second << endl;
    }
}

int main() {

    // Insert an element
    map<string, int> ageMap;
    ageMap.insert(make_pair("Alice", 30));
    ageMap.insert(pair<string, int>("Bob", 25));

    // Access an element
    for (const auto& pair : ageMap) {
        cout << pair.first << " is " << pair.second << " years old." << endl;
    }

    // Count elements
    if (ageMap.count("Alice")) {
        cout << "Alice is found in the map." << endl;
    } else {
        cout << "Alice is not found in the map." << endl;
    }

    // Find elements
    auto it = ageMap.find("Bob");
    if (it != ageMap.end()) {
        cout << "Found Bob, age: " << it->second << endl;
    } else {
        cout << "Bob is not found in the map." << endl;
    }

    //Assign a value
    ageMap["Charlie"] = 40;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Tuple



#include <tuple>

tuple<int, double, string> t1(1, 3.14, "example");
tuple<int, double, string> t2 = make_tuple(2, 2.71, "tuple");

int a = get<0>(t1);  // a = 1
double b = get<1>(t1);  // b = 3.14
string c = get<2>(t1);  // c = "example"

auto [x, y, z] = t1;


Enter fullscreen mode Exit fullscreen mode

Pair



#include <utility> 

pair<int,string> p1(1, "hello");
pair<int,string> p2 = make_pair(2, "world");
vector<pair<int,int>> vc;


Enter fullscreen mode Exit fullscreen mode

File I/O



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

int main() {
    ofstream outFile("example.txt");
    outFile << "Hello, file I/O!" << endl;
    outFile.close();

    ifstream inFile("example.txt");
    string line;
    while (getline(inFile, line)) {
        cout << line << endl;
    }
    inFile.close();

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Exception Handling



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

int divide(int a, int b) {
    if (b == 0) {
        throw invalid_argument("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        cout << "Result: " << result << endl;
    } catch (const invalid_argument& e) {
        cout << "Error: " << e.what() << endl;
    }

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Switch Statement



#include <iostream>
using namespace std;

int main() {
    int day = 3;
    switch (day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid day" << endl;
            break;
    }

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Default Arguments:

Default argument is a value provided in a function declaration that is used when the caller of the function does not provide a corresponding argument.
(Note: The trailing argument will be the default argument)



void greet(std::string name = "Guest") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

int main() {
    // Calling greet without providing any arguments
    greet(); // Output: Hello, Guest!

    // Calling greet with an argument
    greet("Alice"); // Output: Hello, Alice!

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Normal Pointers



int *ptr[10]; // An array of 10 integer pointers.
int (*ptr)[10]; // A pointer to an array of 10 integers.


Enter fullscreen mode Exit fullscreen mode

Basic Pointer Usage



#include <iostream>
using namespace std;

int main() {
    int value = 10;
    int* ptr = &value;

    cout << "Value: " << *ptr << endl;
    cout << "Address of value: " << ptr << endl;

    *ptr = 20; // Modify the value using the pointer
    cout << "Modified Value: " << value << endl;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Pointer Arithmetic



#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int* ptr = arr;// ptr points to first address

    for (int i = 0; i < 5; ++i) {
        cout << *(ptr + i) << " ";
    }
    cout << endl;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Lower and Upper case:



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

int main() {
    char one='G';
    char three='d';
    //returns ascii value
    cout<<tolower(one)<<endl;
    //returns lower case letter
    cout<<(char)tolower(one)<<endl;
    //returns upper case letter
    cout<<(char)toupper(three)<<endl;

    string two="HSLL";
    string res;
    for(char each:two){
        res+=(char)tolower(each);
    }
    cout<<res<<endl;

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Datatype Check



#include <iostream>
#include <cctype>  

int main() {
    char ch = '5';
    if (isalnum(ch)) {
        //alphanumeric 
    }else if (isdigit(ch)) {
        //numeric
    }else if (isalpha(ch)) {
        //alphabetic
    }
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Conversion



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

int main() {
    // String to Integer conversion
    string str = "1234";
    int num = stoi(str);

    // Integer to String conversion
    int anotherNum = 5678;
    string anotherStr = to_string(anotherNum);

    return 0;
}


Enter fullscreen mode Exit fullscreen mode

Common Mistakes:

1)Avoid Division by Zero:
Division by zero is mathematically undefined and causes a program to crash or produce unpredictable results.

2)Overflow check:

Image description



    int reverse(int x) {
        int reverse = 0;
        int sign=1;
        if(x<0){
            sign=-1;
        }
        x = abs(x);

        while (x != 0) {
            int digit = x % 10;

            //Overflow check
            if (reverse > (INT_MAX - digit) / 10) {
                return 0;
            }
            reverse = reverse * 10 + digit;
            x /= 10; 
        }

        return reverse * sign;
    }


Enter fullscreen mode Exit fullscreen mode

Image description

Right to Left

Image description

Image description

Pragma

It is a directive that provides additional information to the compiler. Normally, variables are stored in memory in below fashion.



struct Test
{
   char AA;
   char CC;
   int BB;
};

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) |
| CC(1) | pad.................. |


Enter fullscreen mode Exit fullscreen mode

pragma pack(1)



|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |


Enter fullscreen mode Exit fullscreen mode

pragma pack(2)



|   1   |   2   |

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |


Enter fullscreen mode Exit fullscreen mode

Top comments (0)