cpp / beginner
Snippet
Variables and Constants in C++
Variables store data that can change during program execution, while constants hold fixed values that cannot be modified after initialization. This example demonstrates different data types: int for whole numbers, float for decimal numbers (single precision), double for higher precision decimals, bool for true/false values, and string for text. The const keyword protects the NAME constant from accidental modification - the compiler would reject any attempt to change it.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>using namespace std;int main() {int age = 25;const string NAME = "Max";float height = 1.75f;double preciseValue = 3.1415926535;bool isStudent = true;cout << "Name: " << NAME << endl;cout << "Age: " << age << endl;cout << "Height: " << height << " m" << endl;cout << "Pi: " << preciseValue << endl;cout << "Is Student: " << (isStudent ? "Yes" : "No") << endl;age = 26;// NAME = "Anna"; // Error! Cannot change constcout << "New Age: " << age << endl;return 0;}
Breakdown
1
int age = 25;
Integer variable storing a whole number value of 25
2
const string NAME = "Max";
Constant string that cannot be changed after initialization
3
float height = 1.75f;
Float variable with 'f' suffix indicating single precision decimal
4
bool isStudent = true;
Boolean variable holding either true or false
5
age = 26;
Successfully modifies age since it's a regular variable
6
// NAME = "Anna";
Commented out line would cause compiler error - const values are immutable