Declaring Variables
In C++ you declare a variable with its type, then its name, and optionally initialize it:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 25;
double price = 9.99;
bool isActive = true;
char grade = 'A';
string name = "Alice";
cout << name << " is " << age << endl;
return 0;
}
Fundamental Types
| Type | Size | Example |
|---|---|---|
| int | 4 bytes | 42, -7 |
| long long | 8 bytes | 9999999999LL |
| float | 4 bytes | 3.14f |
| double | 8 bytes | 3.14159 |
| char | 1 byte | 'X' |
| bool | 1 byte | true / false |
| string | dynamic | "hello" |
Constants
const double PI = 3.14159265;
constexpr int MAX = 100; // compile-time constant (preferred)
// PI = 3.0; // ❌ error
auto Keyword
auto count = 10; // int
auto price = 9.99; // double
auto name = string("Hi"); // string
// auto with range-based for
vector<int> nums = {1, 2, 3};
for (auto n : nums) cout << n << " ";
Type Casting
double x = 9.7;
int n = static_cast<int>(x); // 9 — preferred C++ cast
int m = (int)x; // C-style cast — avoid in modern C++
Input / Output
int a;
string s;
cin >> a; // read integer
cin >> s; // read word
getline(cin, s); // read full line
cout << "a = " << a << endl;