C++ Cheat Sheet Printable

5 min read Jul 01, 2024
C++ Cheat Sheet Printable

C++ Cheat Sheet (Printable)

This cheat sheet provides a concise overview of essential C++ concepts and syntax, designed for quick reference during coding.

Data Types

Data Type Description Size (bytes)
char Character 1
int Integer 4
float Single-precision floating-point 4
double Double-precision floating-point 8
bool Boolean (true/false) 1
void Represents the absence of a value -

Operators

Operator Description Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus (remainder) x % y
+= Add and assign x += y (equivalent to x = x + y)
-= Subtract and assign x -= y (equivalent to x = x - y)
*= Multiply and assign x *= y (equivalent to x = x * y)
/= Divide and assign x /= y (equivalent to x = x / y)
%= Modulus and assign x %= y (equivalent to x = x % y)
++ Increment x++ (post-increment), ++x (pre-increment)
-- Decrement x-- (post-decrement), --x (pre-decrement)
== Equality x == y
!= Inequality x != y
< Less than x < y
> Greater than x > y
<= Less than or equal to x <= y
>= Greater than or equal to x >= y
&& Logical AND x && y
` `
! Logical NOT !x

Control Flow

  • if-else statement:
if (condition) {
  // Code to execute if condition is true
} else {
  // Code to execute if condition is false
}
  • switch statement:
switch (expression) {
  case value1:
    // Code to execute if expression equals value1
    break;
  case value2:
    // Code to execute if expression equals value2
    break;
  default:
    // Code to execute if expression doesn't match any case
}
  • for loop:
for (initialization; condition; increment) {
  // Code to execute in loop
}
  • while loop:
while (condition) {
  // Code to execute in loop
}
  • do-while loop:
do {
  // Code to execute in loop
} while (condition);

Arrays

  • Declaration:
int numbers[5]; // Array of 5 integers
  • Accessing elements:
int firstElement = numbers[0];

Pointers

  • Declaration:
int *ptr; // Pointer to an integer
  • Dereference:
int value = *ptr; // Accessing the value pointed to by ptr

Functions

  • Declaration:
int sum(int a, int b); // Function declaration
  • Definition:
int sum(int a, int b) {
  return a + b;
}
  • Calling:
int result = sum(2, 3); // Function call

Classes and Objects

  • Class declaration:
class Car {
public:
  string model;
  int year;
  void display() {
    cout << "Model: " << model << endl;
    cout << "Year: " << year << endl;
  }
};
  • Object creation:
Car myCar;
myCar.model = "Ford";
myCar.year = 2023;
myCar.display();

Namespaces

  • Declaration:
namespace MyNamespace {
  // Code within the namespace
}
  • Accessing elements:
MyNamespace::functionName();

This cheat sheet provides a basic foundation in C++. Remember to consult comprehensive documentation and tutorials for a deeper understanding and further exploration of the language.

Latest Posts


Featured Posts