C++ CheatSheet

Are you a C++ programmer looking to take your skills to the next level? Look no further than this sophisticated and comprehensive C++ cheat sheet. Crafted with the expertise of seasoned developers, this cheat sheet offers an in-depth look at all aspects of C++ programming, from basic syntax to advanced topics like object-oriented programming and template metaprogramming.

Featuring detailed explanations and code examples for each concept, this cheat sheet is designed to help you quickly master the intricacies of C++ programming. Whether you're a seasoned pro or just starting out, you'll find everything you need to know about data types, control structures, functions, classes, and more.

With its elegant design and easy-to-read format, this cheat sheet is perfect for quick reference during coding sessions and study sessions alike. So why settle for ordinary resources? Download your copy of this exceptional C++ cheat sheet today and gain the expertise you need to create sophisticated and powerful programs like never before.


Table of Content




# Getting started C++


What is C++ ?

C++ (/?si??pl?s?pl?s/) is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significantly over time, and modern C++ now has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. It is almost always implemented as a compiled language, and many vendors provide C++ compilers, including the Free Software Foundation, LLVM, Microsoft, Intel, Oracle, and IBM, so it is available on many platforms.

  • C++ is a cross-platform language that can be used to create high-performance applications.
  • C++ was developed by Bjarne Stroustrup, as an extension to the C language.
  • C++ gives programmers a high level of control over system resources and memory.
  • The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.

Why C++ ?

  • C++ is one of the world's most popular programming languages.
  • C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
  • C++ is an object-oriented programming language that gives a clear structure to programs and allows code to be reused, lowering development costs.
  • C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
  • C++ is fun and easy to learn!
  • As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

helloworld.cpp

#include 

int main() {
    std::cout << "Hello World\n";
    return 0;
}

Compiling and running

$ g++ helloworld.cpp -o helloworld

$ ./helloworld

Hello World

Variables

int number = 5;       // Integer
float f = 0.95;       // Floating number
double PI = 3.14159;  // Floating number
char yes = 'Y';       // Character
std::string s = "ME"; // String (text)
bool isRight = true;  // Boolean

// Constants
const float RATE = 0.8;

// c++ 11 syntax
int age {25};         // Since C++11
std::cout << age;     // Print 25

Primitive Data Types

Data Type Size Range
int 4 bytes -231 to 231-1
float 4 bytes N/A
double 8 bytes N/A
char 1 byte -128 to 127
bool 1 byte true / false
void N/A N/A
wchar_t 2 or 4 bytes 1 wide character

User Input

int num;

std::cout << "Type a number: ";
std::cin >> num;

std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;

// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++

/* This is a multiple line comment
   in C++ */

If statement

if (x == 500) {
    // do something in here
}

Loops

for (int i = 0; i < 500; i++) {
    std::cout << i << "\n";
}

Functions

#include 
 
void helloworld(); // Declaring
 
int main() {  // main function
    helloworld();    // Calling
}
 
void helloworld() { // Defining
    std::cout << "Hello World!\n";
}

References

int i = 1;
int& ri = i; // ri is a reference to i

ri = 2; // i is now changed to 2
std::cout << "i=" << i;

i = 3;   // i is now changed to 3
std::cout << "ri=" << ri;

Namespaces

#include 
namespace ns1 {int val(){return 5;}}
int main()
{
    std::cout << ns1::val();
}

// -------------------
#include 
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
    cout << val(); 
}

# Arrays in C++


Declaration

int marks[4]; // Declaration
marks[0] = 91;
marks[1] = 92;
marks[2] = 93;
marks[3] = 94;

// Declare and initialize
int marks[4] = {91, 92, 93, 94};
int marks[]  = {91, 92, 93, 94};

// With empty members
int marks[3] = {91, 94};
std::cout << marks[2]; // Outputs: 0

Manipulation


?????????????????????????????????????
| 92  | 97  | 98  | 99  | 98  | 94  |
?????????????????????????????????????
0     1     2     3     4     5

int marks[6] = {92, 97, 98, 99, 98, 94};

// Print first element
std::cout << marks[0];

// Change 2th element to 99
marks[1] = 99;

// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'H', 'e', 'l'};

// Range based for loop
for (const int &n : ref) {
    std::cout << std::string(1, n);
}

// Traditional for loop
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}

Multidimensional


     j0   j1   j2   j3   j4   j5
   ???????????????????????????????
i0 | 1  | 2  | 3  | 4  | 5  | 6  |
   ???????????????????????????????
i1 | 6  | 5  | 4  | 3  | 2  | 1  |
   ???????????????????????????????


int x[2][6] = {
    {1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
        std::cout << x[i][j] << " ";
    }
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

# Conditionals in C++


If Clause

// Syntax
if (a == 500) {
    // do something at here
}

// Example
int number = 20;

if (number % 2 == 0)
{
    std::cout << "even";
}
else
{
    std::cout << "odd";
}

// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
    std::cout << "You are Super Good";
}
else if (score >= 90) {
    std::cout << "You are Excellent ^^!";
}
else if (score >= 80) {
    std::cout << "You are Very Good";
}
else if (score >= 70) {
    std::cout << "Good!!";
}
else if (score >= 60)
    std::cout << "OK!!";
else
    std::cout << "Ohhh What?";

Operators

Relational Operators

a == b a is equal to b
a != b a is NOT equal to b
a < b a is less than b
a > b a is greater b
a <= b a is less than or equal to b
a >= b a is greater or equal to b

Assignment Operators

a += b Aka a = a + b
a -= b Aka a = a - b
a *= b Aka a = a * b
a /= b Aka a = a / b
a %= b Aka a = a % b

Logical Operators

exp1 && exp2 Both are true (AND)
exp1 || exp2 Either is true (OR)
!exp exp is false (NOT)

Bitwise Operators

a & b Binary AND
a | b Binary OR
a ^ b Binary XOR
a ~ b Binary One's Complement
a << b Binary Shift Left
a >> b Binary Shift Right

Ternary Operator


           ??? True ???
Result = Condition ? Exp1 : Exp2;
           ?????? False ??????


int x = 3, y = 5, max;
max = (x > y) ? x : y;

// Outputs: 5
std::cout << max << std::endl;

// -------------------
int x = 3, y = 5, max;
if (x > y) {
    max = x;
} else {
    max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
    case 0:
        std::cout << "Number is Zero";
        break;
    case 1:
        std::cout << "Number is One";
        break;
    case 2:
        std::cout << "Number is Two";
        break;
    case 3:
        std::cout << "Number is Three";
        break;
    default:
        std::cout << "Ohh What?";
        break;
}

# Loops in C++


While

int i = 0;
while (i < 7) {
    std::cout << i++;
}

// Outputs: 0123456

Do-while

int i = 1;
do {
    std::cout << i++;
} while (i <= 6);

// Outputs: 123456

Continue statements

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
    std::cout << "infinite loop";
}


for (;;) {
    std::cout << "infinite loop";
}


for(int i = 1; i > 0; i++) {
    std::cout << "infinite loop";
}

for_each (Since C++ 11)

#include 

void print(int num)
{
    std::cout << num << std::endl;
}

int main()
{
    int arr[4] = {1, 2, 3, 4 };
    std::for_each(arr, arr + 4, print);
    return 0;
}

Range-based (Since C++ 11)

int num_array[] = {1, 2, 3, 4, 5, 6};
for (int n : num_array) {
    std::cout << n << " ";
}
// Outputs: 1 2 3 4 5 6


std::string hello = "Google.com";
for (char c: hello)
{
    std::cout << c << " ";
}
// Outputs: G o o g l e . c o m

Break statements

int password, times = 0;
while (password != 1234) {
    if (times++ >= 3) {
        std::cout << "Locked!\n";
        break;
    }
    std::cout << "Password: ";
    std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
    std::cout << "i=" << i << ",";
    std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

# Functions in C++


Arguments & Returns

#include 

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

int main() {
    std::cout << add(30, 20); 
}
// output: 50

Overloading

void fun(string a, string b) {
    std::cout << a + " " + b;
}


void fun(string a) {
    std::cout << a;
}


void fun(int a) {
    std::cout << a;
}

Built-in Functions

#include 
#include  // import library
 
int main() {
    // sqrt() is from cmath
    std::cout << sqrt(9);
}

# Preprocessor in C++


Includes

#include "iostream"
#include 

Defines

#define FOO
#define FOO "hello"

#undef FOO

If

#ifdef DEBUG
  console.log('hi');
#elif defined VERBOSE
  ...
#else
  ...
#endif

Error

#if VERSION == 2.0
  #error Unsupported
  #warning Not really supported
#endif

Macro

#define DEG(x) ((x) * 57.29)

Token concat

#define DST(name) name##_s name##_t
DST(object);   #=> object_s object_t;

Stringification

#define STR(name) #name
char * a = STR(object);   #=> char * a = "object";

File and Line

#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

# Miscellaneous




Best Suggest