C++ Cours

C++ Variables and Data Types

Tutoriel Python 3 pour débutants.

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

TypeSizeExample
int4 bytes42, -7
long long8 bytes9999999999LL
float4 bytes3.14f
double8 bytes3.14159
char1 byte'X'
bool1 bytetrue / false
stringdynamic"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;