QuickRef.
ME Search for cheatsheet ⌘K Sponsor Edit page
C++ cheatsheet
C++ quick reference cheat sheet that provides basic syntax and methods.
# Getting started
hello.cpp Variables Primitive Data Types
#include <iostream> int number = 5; // Integer Data Type Size Range
float f = 0.95; // Floating number 31 to
int 4 bytes -2 231-1
int main() { double PI = 3.14159; // Floating number
std::cout << "Hello QuickRef\n"; char yes = 'Y'; // Character
float 4 bytes N/A
return 0; std::string s = "ME"; // String (text)
} bool isRight = true; // Boolean
double 8 bytes N/A
// Constants char 1 byte -128 to
127
Compiling and running
const float RATE = 0.8;
$ g++ hello.cpp -o hello
bool 1 byte true / false
$ ./hello int age {25}; // Since C++11
void N/A N/A
Hello QuickRef std::cout << age; // Print 25
or
wchar_t 2 4 bytes 1 wide character
User Input Swap Comments
int num; int a = 5, b = 10, temp; // A single one line comment in C++
temp = a;
std::cout << "Type a number: "; a = b; /* This is a multiple line comment
std::cin >> num; b = temp; in C++ */
std::cout << "You entered " << num; // Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;
If statement Loops Functions
if (a == 10) { for (int i = 0; i < 10; i++) { #include <iostream>
// do something std::cout << i << "\n";
} } void hello(); // Declaring
int main() { // main function
hello(); // Calling
}
void hello() { // Defining
std::cout << "Hello QuickRef!\n";
}
See: Conditionals See: Loops See: Functions
References Namespaces
int i = 1; #include <iostream>
int& ri = i; // ri is a reference to i namespace ns1 {int val(){return 5;}}
int main()
ri = 2; // i is now changed to 2 {
std::cout << "i=" << i; std::cout << ns1::val();
}
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;
#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
cout << val();
}
ri and i refer to the same memory location. Namespaces allow global identifiers under a name
# C++ Arrays
Declaration Manipulation Displaying
int marks[3]; // Declaration ┌─────┬─────┬─────┬─────┬─────┬─────┐ char ref[5] = {'R', 'e', 'f'};
marks[0] = 92; | 92 | 97 | 98 | 99 | 98 | 94 |
marks[1] = 97; └─────┴─────┴─────┴─────┴─────┴─────┘ // Range based for loop
marks[2] = 98; 0 1 2 3 4 5 for (const int &n : ref) {
std::cout << std::string(1, n);
// Declare and initialize }
int marks[6] = {92, 97, 98, 99, 98, 94};
int marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98}; // Traditional for loop
// Print first element
for (int i = 0; i < sizeof(ref); ++i) {
std::cout << marks[0];
// With empty members std::cout << ref[i];
int marks[3] = {92, 97}; }
// Change 2th element to 99
std::cout << marks[2]; // Outputs: 0
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];
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
# C++ Conditionals
If Clause Else if Statement _ Operators
Relational Operators
if (a == 10) { int score = 99;
// do something if (score == 100) { a == b a is equal to b
} std::cout << "Superb";
} a != b a is NOT equal to b
else if (score >= 90) {
int number = 16;
std::cout << "Excellent"; a < b a is less than b
}
if (number % 2 == 0)
else if (score >= 80) { a > b a is greater b
{
std::cout << "Very Good";
std::cout << "even"; a <= b a is less than or equal to b
}
}
else if (score >= 70) {
else a >= b a is greater or equal to b
std::cout << "Good";
{
} Assignment Operators
std::cout << "odd";
else if (score >= 60)
}
std::cout << "OK"; a += b Aka a = a + b
else
// Outputs: even a -= b Aka a = a - b
std::cout << "What?";
a *= b Aka a = a * b
a /= b Aka a = a / b
Ternary Operator Switch Statement
a %= b Aka a = a % b
┌── True ──┐ int num = 2;
Result = Condition ? Exp1 : Exp2; switch (num) { Logical Operators
└───── False ─────┘ case 0:
std::cout << "Zero";
exp1 && exp2 Both are true (AND)
break;
int x = 3, y = 5, max; exp1 || exp2 Either is true (OR)
case 1:
max = (x > y) ? x : y;
std::cout << "One";
!exp exp is false (NOT)
break;
// Outputs: 5
case 2: Bitwise Operators
std::cout << max << std::endl;
std::cout << "Two";
std::cout << Two ;
break; a & b Binary AND
int x = 3, y = 5, max; case 3:
a | b Binary OR
if (x > y) { std::cout << "Three";
max = x; break;
a ^ b Binary XOR
} else { default:
max = y; std::cout << "What?";
a ~ b Binary One's Complement
} break;
// Outputs: 5 } a << b Binary Shift Left
std::cout << max << std::endl;
a >> b Binary Shift Right
# C++ Loops
While Do-while Continue statements
int i = 0; int i = 1; for (int i = 0; i < 10; i++) {
while (i < 6) { do { if (i % 2 == 0) {
std::cout << i++; std::cout << i++; continue;
} } while (i <= 5); }
std::cout << i;
// Outputs: 012345 // Outputs: 12345 } // Outputs: 13579
Infinite loop for_each (Since C++11) Range-based (Since C++11)
while (true) { // true or 1 #include <iostream> int num_array[] = {1, 2, 3, 4, 5};
std::cout << "infinite loop"; for (int n : num_array) {
} void print(int num) std::cout << n << " ";
{ }
std::cout << num << std::endl; // Outputs: 1 2 3 4 5
for (;;) {
}
std::cout << "infinite loop";
} std::string hello = "QuickRef.ME";
int main()
for (char c: hello)
{
{
for(int i = 1; i > 0; i++) { int arr[4] = {1, 2, 3, 4 };
std::cout << c << " ";
std::cout << "infinite loop"; std::for_each(arr, arr + 4, print);
}
} return 0;
// Outputs: Q u i c k R e f . M E
}
Break statements Several variations
int password, times = 0; for (int i = 0, j = 2; i < 3; i++, j--){
while (password != 1234) { std::cout << "i=" << i << ",";
if (times++ >= 3) { std::cout << "j=" << j << ";";
std::cout << "Locked!\n"; }
break; // Outputs: i=0,j=2;i=1,j=1;i=2,j=0;
}
std::cout << "Password: ";
std::cin >> password; // input
}
# C++ Functions
Arguments & Returns Overloading Built-in Functions
#include <iostream> void fun(string a, string b) { #include <iostream>
std::cout << a + " " + b; #include <cmath> // import library
int add(int a, int b) { }
return a + b; void fun(string a) { int main() {
} std::cout << a; // sqrt() is from cmath
} std::cout << sqrt(9);
int main() { void fun(int a) { }
std::cout << add(10, 20); std::cout << a;
} }
add is a function taking 2 ints and returning int
# C++ Classes & Objects
If statement If statement If statement
If statement
# C++ Preprocessor
Preprocessor Includes Defines
if elif #include "iostream" #define FOO
#include <iostream> #define FOO "hello"
else endif
#undef FOO
ifdef ifndef
define undef
If Error
include line
#ifdef DEBUG #if VERSION == 2.0
console.log('hi'); #error Unsupported
error pragma
#elif defined VERBOSE #warning Not really supported
defined __has_include ... #endif
#else
__has_cpp_attribute export ...
#endif Macro
import module
#define DEG(x) ((x) * 57.29)
Token concat Stringification file and line
#define DST(name) name##_s name##_t #define STR(name) #name #define LOG(msg) console.log(__FILE__, __LI
DST(object); #=> object_s object_t; char * a = STR(object); #=> char * a = "o #=> console.log("file.txt", 3, "hey")
# Miscellaneous
Escape Sequences Keywords
\b Backspace alignas alignof and and_eq asm
\f Form feed atomic_cancel atomic_commit atomic_noexcept auto bitand
\n Newline bitor bool break case catch
\r Return char char8_t char16_t char32_t class
\t Horizontal tab compl concept const consteval constexpr
\v Vertical tab constinit const_cast continue co_await co_return
\\ Backslash co_yield decltype default delete do
\' Single quotation mark double dynamic_cast else enum explicit
export extern false float for
\" Double quotation mark
friend goto if inline int
\? Question mark
long mutable namespace new noexcept
\0 Null Character
not not_eq nullptr operator or
Preprocessor or_eq private protected public reflexpr
if elif register reinterpret_cast requires return short
else endif signed sizeof static static_assert static_cast
ifdef ifndef struct switch synchronized template this
define undef thread_local throw true try typedef
include line typeid typename union unsigned using
error pragma virtual void volatile wchar_t while
defined __has_include xor xor_eq final override transaction_safe
__has_cpp_attribute export transaction_safe_dynamic
import module
# Also see
C++ Infographics & Cheat Sheets (hackingcpp.com)
C++ reference (cppreference.com)
C++ Language Tutorials (cplusplus.com)
Top Cheatsheet Recent Cheatsheet
QuickRef.ME
Python Cheatsheet Vim Cheatsheet Neo4j Cheatsheet HTML Cheatsheet Share quick reference and cheat sheet for
developers.
Quick Reference Quick Reference Quick Reference Quick Reference
#Notes
Bash Cheatsheet JavaScript Cheatsheet GraphQL Cheatsheet Chmod Cheatsheet
Quick Reference Quick Reference Quick Reference Quick Reference
© 2021 QuickRef.ME, All rights reserved.