<!-- Example --> <pre> #include <iostream> using namespace std; int main() { cout << "Hello, C++!" << endl; return 0; } </pre>
<pre> #include <iostream> int main() { std::cout << "Welcome to C++!" << std::endl; return 0; } </pre>
<pre> // This is a single-line comment /* This is a multi-line comment */ </pre>
<pre> int age = 25; float weight = 70.5; char grade = 'A'; </pre>
<pre> int x; // Declaration x = 10; // Initialization int y = 20; // Declaration with initialization </pre>
<pre> const float PI = 3.14; </pre>
<pre> int a = 5; float b = a; // Implicit conversion int c = (int)3.7; // Explicit conversion (type casting) </pre>
<pre> int globalVar = 100; void show() { int localVar = 50; } </pre>
<pre> auto num = 42; // Treated as int auto name = "Tom"; // Treated as const char* </pre>
<pre> cout << sizeof(int); // Outputs 4 cout << sizeof(double); // Outputs 8 </pre>
<pre> int x = 10; int y = 5; int result = x + y; cout << result; // Output: 15 </pre>
<pre> int a = 20; int b = 6; cout << a / b; // Output: 3 cout << a % b; // Output: 2 </pre>
<pre> int a = 5; a += 10; // Equivalent to a = a + 10; cout << a; // Output: 15 </pre>
<pre> int x = 5, y = 10; cout << (x < y); // Output: 1 (true) </pre>
<pre> int a = 5; int b = 10; bool result = (a < b) && (b > 0); // true </pre>
<pre> int a = 3; a++; // a becomes 4 --a; // a becomes 3 again </pre>
<pre> int x = 8; int y = (x > 5) ? 100 : 0; cout << y; // Output: 100 </pre>
<pre> int a = 6; // 0110 int b = 3; // 0011 cout << (a & b); // Output: 2 (0001) </pre>
<pre> int result = 10 + 2 * 3; // 16 int fixed = (10 + 2) * 3; // 36 </pre>
<pre> int a = 5; int b = 10; int sum = a + b; // Expression: a + b </pre>
<pre> int x = 10; if (x > 5) { cout << "x is greater than 5"; } </pre>
<pre> int score = 90; if (score >= 80) { cout << "Excellent!"; } </pre>
<pre> int num = 3; if (num % 2 == 0) { cout << "Even"; } else { cout << "Odd"; } </pre>
<pre> int marks = 75; if (marks >= 90) { cout << "A"; } else if (marks >= 75) { cout << "B"; } else { cout << "C"; } </pre>
<pre> int day = 2; switch(day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; default: cout << "Other Day"; } </pre>
<pre> int i = 1; while (i <= 3) { cout << i << " "; i++; } </pre>
<pre> int i = 1; do { cout << i << " "; i++; } while (i <= 3); </pre>
<pre> for (int i = 1; i <= 5; i++) { cout << i << " "; } </pre>
<pre> for (int i = 1; i <= 5; i++) { if (i == 3) break; cout << i << " "; } </pre>
<pre> for (int i = 1; i <= 5; i++) { if (i == 3) continue; cout << i << " "; } </pre>
#include <iostream> using namespace std; void greet() { cout << "Hello from a function!" << endl; }
#include <iostream> using namespace std; void sayHello() { cout << "Hello!" << endl; } int main() { sayHello(); // function call return 0; }
void greetUser(string name) { cout << "Welcome, " << name << "!" << endl; }
int add(int a, int b) { return a + b; }
void greet(); // prototype int main() { greet(); return 0; } void greet() { cout << "Hello!" << endl; }
inline int square(int x) { return x * x; }
void greet(string name = "Guest") { cout << "Hello, " << name << endl; }
void show(int x) { cout << "Integer: " << x << endl; } void show(string text) { cout << "String: " << text << endl; }
int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); }
int globalVar = 100; void demo() { int localVar = 50; cout << localVar << " " << globalVar; }
int numbers[5] = {1, 2, 3, 4, 5}; cout << numbers[0]; // Output: 1
int data[3]; data[0] = 10; data[1] = 20; data[2] = 30;
int scores[] = {80, 90, 100}; cout << scores[1]; // Output: 90
int nums[] = {5, 10, 15, 20}; for (int i = 0; i < 4; i++) { cout << nums[i] << " "; }
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; cout << matrix[1][2]; // Output: 6
void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } }
#includestring name = "Alice"; cout << name;
char name[] = "Bob"; cout << name; // Output: Bob
string word = "Hello"; cout << word.length(); // Output: 5
string a = "apple"; string b = "banana"; if (a < b) { cout << "apple comes first"; }
class Car { public: string model; };
class Animal { public: string name; }; int main() { Animal dog; dog.name = "Buddy"; cout << dog.name; }
class Box { private: int length; public: void setLength(int l) { length = l; } };
class Person { public: Person() { cout << "Constructor called!"; } };
class Person { public: ~Person() { cout << "Destructor called!"; } };
class Circle { public: void draw() { cout << "Drawing circle"; } };
class Book { public: string title; }; int main() { Book b; b.title = "C++ Guide"; cout << b.title; }
class BankAccount { private: int balance; public: void setBalance(int b) { balance = b; } int getBalance() { return balance; } };
class Remote { public: void powerOn() { cout << "Power ON"; } };
class Student { public: string name; int age; void display() { cout << name << " is " << age << " years old."; } };
class Vehicle { public: void move() { cout << "Moving..."; } }; class Car : public Vehicle { };
class A { }; class B : public A { }; // Single inheritance
class Animal { public: void speak() { cout << "Animal speaks"; } }; class Dog : public Animal { };
class A { }; class B : public A { }; class C : public B { };
class A { }; class B { }; class C : public A, public B { };
class Parent { }; class Child1 : public Parent { }; class Child2 : public Parent { };
class A { }; class B : public A { }; class C { }; class D : public B, public C { };
Dog d; d.speak(); // Inherited from Animal
class Base { public: Base() { cout << "Base constructor"; } }; class Derived : public Base { public: Derived() { cout << "Derived constructor"; } };
class A { public: void show() { cout << "Base"; } }; class B : public A { public: void show() { cout << "Derived"; } };
class Shape { public: void draw() { cout << "Drawing shape"; } };
void print(int x) { cout << "Int: " << x; } void print(string s) { cout << "String: " << s; }
int add(int a, int b) { return a + b; } float add(float a, float b) { return a + b; }
class Point { public: int x; Point operator+(Point p) { Point temp; temp.x = x + p.x; return temp; } };
class Base { public: virtual void show() { cout << "Base"; } };
class Derived : public Base { public: void show() override { cout << "Derived"; } };
class Animal { public: virtual void sound() = 0; // Pure virtual };
class IPrintable { public: virtual void print() = 0; };
void hello() { cout << "Hi!"; } int main() { void (*ptr)() = hello; ptr(); // Call via pointer }
// Automatically managed by compiler, not directly used in code
#includeusing namespace std;
ofstream file("example.txt"); file << "Hello File!"; file.close();
ofstream file("data.txt"); file << "This is a test."; file.close();
ifstream file("data.txt"); string text; while (file >> text) { cout << text << " "; } file.close();
ifstream file("story.txt"); string line; getline(file, line); cout << line;
ifstream file("log.txt"); if (file.is_open()) { cout << "Opened!"; }
ofstream file("data.txt", ios::app); file << "\nNew entry"; file.close();
ofstream file("log.txt", ios::out | ios::app);
char ch; file.get(ch); cout << ch;
file.close();
template <typename T> T add(T a, T b) { return a + b; }
template <class T> T max(T a, T b) { return (a > b) ? a : b; }
template <class T> class Box { public: T value; };
template <> class Box<int> { public: int value; void show() { cout << "Int Box"; } };
template <int size> class Array { int arr[size]; };
auto result = add(5, 10); // T is int
template <typename T, typename... Args> void func(T first, Args... args) { cout << first << endl; func(args...); }
template <template <typename> class Container, typename T> class Wrapper { Container<T> c; };
try { // code that may throw exception } catch (exception &e) { cout << e.what(); }
throw runtime_error("Error occurred");
try { // code } catch (int e) { cout << "Int exception: " << e; }
try { // code } catch (int e) { // handle int exception } catch (runtime_error &e) { // handle runtime_error }
try { // code } catch (...) { cout << "Unknown exception"; }
throw logic_error("Logic error");
class MyException : public exception { public: const char* what() const noexcept override { return "My custom exception"; } };
#include <vector> using namespace std;
vector<int> nums = {1, 2, 3, 4};
vector<int> :: iterator it = nums.begin(); cout << *it;
sort(nums.begin(), nums.end());
struct Compare { bool operator()(int a, int b) { return a > b; } };
auto add = [](int a, int b) { return a + b; }; cout << add(2, 3);
#include <memory> using namespace std;
unique_ptr<int> p1(new int(5)); cout << *p1;
shared_ptr<int> p2 = make_shared<int>(10);
unique_ptr<FILE, decltype(&fclose)> fp(fopen("file.txt", "r"), &fclose);
#include <thread> using namespace std;
void task() { cout << "Thread running"; } int main() { thread t(task); t.join(); }
void printNum(int n) { cout << n; } thread t(printNum, 5);
#include <mutex> mutex mtx; mtx.lock(); // critical section mtx.unlock();
auto add = [](int a, int b) { return a + b; }; cout << add(2, 3); // Output: 5
[&] (int x) { cout << x; };
int n = 5; auto f = [n]() { cout << n; };
int x = 10; auto f = [x]() mutable { x++; cout << x; };
auto f = [](int x) -> double { return x / 2.0; };
vector<int> v = {1, 2, 3}; sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
#include <functional> std::function<int(int, int)> func = add;
std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = std::move(v1);
void func(std::string&& s) { cout << s; }
class MyClass { public: MyClass(MyClass&& other) { // move resources } };
MyClass& operator=(MyClass&& other) { // move resources return *this; }
std::string s1 = "Hello"; std::string s2 = std::move(s1);
namespace MyNamespace { int x; }
using namespace std; cout << "Hello";
namespace A { namespace B { int y; } }
MyNamespace::x = 10;
namespace { int secret; }
void func() { static int count = 0; count++; }
extern int globalVar;
using std::cout;
int* p = new int(5);
int* arr = new int[10];
delete p; delete[] arr;
int* p = arr; p++;
auto x = 10; nullptr; for (auto &item : container) { }
constexpr int square(int x) { return x * x; }
class MyClass { public: MyClass(MyClass&& other) noexcept { // move resources } };
MyClass& operator=(MyClass&& other) noexcept { if (this != &other) { // release current resources // acquire other's resources } return *this; }
std::string s1 = "Hello"; std::string s2 = std::move(s1);
constexpr int square(int x) { return x * x; }
constexpr int size = 10; int arr[size];
export module MyModule;
import MyModule;
template <typename T> void func(T t) { if constexpr (std::is_integral_v<T>) { cout << "Integral"; } else { cout << "Not integral"; } }
template <typename T> concept Integral = std::is_integral_v<T>;
template <Integral T> void func(T t) { // ... }
// Example requires C++20 support std::generator<int> counter() { for (int i = 0; i < 10; ++i) co_yield i; }
template <int N> struct Factorial { static constexpr int value = N * Factorial<N-1>::value; }; template <> struct Factorial<0> { static constexpr int value = 1; };
#include <thread> void func() { /* ... */ } std::thread t(func); t.join();
std::mutex mtx; mtx.lock(); // critical section mtx.unlock();
std::lock_guard<std::mutex> lock(mtx); // automatic unlock
struct Compare { bool operator()(int a, int b) const { return a > b; // descending order } }; std::set<int, Compare> s;
std::vector<std::string> v; v.emplace_back("hello");
auto [x, y] = std::make_pair(1, 2); cout << x << y;
std::optional<int> opt = 5; if (opt) cout << *opt;
throw std::runtime_error("Error occurred");
try { // code that might throw } catch (const std::exception& e) { cout << e.what(); }
auto add = [](int a, int b) { return a + b; }; cout << add(2, 3);
int x = 10; auto printX = [x]() { cout << x; };
int x = 5; auto increment = [x]() mutable { x++; cout << x; };
auto print = [](auto value) { cout << value; };
std::vector<int> v = {1, 2, 3}; std::for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
std::unique_ptr<int> ptr = std::make_unique<int>(10);
std::shared_ptr<int> sp1 = std::make_shared<int>(20); auto sp2 = sp1; // shared ownership
template <typename T> concept IntegralOrFloating = std::integral<T> || std::floating_point<T>;
template <typename T> requires std::integral<T> T add(T a, T b) { return a + b; }