0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
C++ · BeginnerSnippet

Simple Function Definition

Functions help organize code into reusable blocks. They can take parameters and return values.

snippet.cpp
cpp
1
2
3
4
5
int add(int a, int b) {
return a + b;
}
int result = add(10, 5);
FunctionsSyntax
C++ · BeginnerSnippet

Conditional Logic with If-Else

Conditional statements allow your program to make decisions based on certain criteria.

snippet.cpp
cpp
1
2
3
4
5
6
7
int score = 85;
if (score >= 50) {
std::cout << "Passed";
} else {
std::cout << "Failed";
}
Control Flow
C++ · BeginnerSnippet

Variables and Data Types

C++ is a strongly typed language, meaning you must declare the type of data a variable will hold.

snippet.cpp
cpp
1
2
3
4
int age = 25;
double price = 19.99;
char grade = 'A';
bool isReady = true;
Data TypesSyntax
C++ · BeginnerSnippet

The Basic Structure of a C++ Program

Every C++ program starts with a main function. We use #include <iostream> to allow us to print text to the console.

snippet.cpp
cpp
1
2
3
4
5
6
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
SyntaxBest Practices
C++ · BeginnerSnippet

Working with Arrays

Arrays are used to store multiple values of the same type in a single variable.

snippet.cpp
cpp
1
2
3
4
int grades[3] = {90, 85, 70};
std::cout << grades[0]; // Prints 90
grades[1] = 95; // Updates the second element
Arrays & ListsSyntax
C++ · BeginnerSnippet

Iterating with For Loops

A for loop repeats a block of code a specific number of times. It is ideal when you know exactly how many iterations are needed.

snippet.cpp
cpp
1
2
3
for (int i = 0; i < 5; ++i) {
std::cout << "Count: " << i << std::endl;
}
Control FlowSyntax
C++ · BeginnerSnippet

The Standard Namespace (std::)

C++ uses namespaces to organize code and avoid naming conflicts. Most standard features are prefixed with 'std::' to indicate they belong to the Standard Library.

snippet.cpp
cpp
1
std::cout << "Hello from the standard namespace!";
SyntaxBest Practices
C++ · BeginnerSnippet

Declaring Constants with const

The 'const' keyword creates a read-only variable. Once initialized, its value cannot be changed, which prevents accidental modifications.

snippet.cpp
cpp
1
2
const double PI = 3.14159;
// PI = 3.14; // This would cause a compiler error
SyntaxBest PracticesData Types