cpp / beginner
Snippet
Variables and Assignment: Storing Data in Memory
Variables are containers for storing data values. In C++, you must declare the type of a variable before using it. The type determines what kind of data can be stored (integers, decimals, characters, or true/false values). Once declared, you can assign new values using the equals sign (=). Different data types serve different purposes: int for whole numbers, double for decimal numbers, char for single characters, and bool for true/false conditions.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>int main() {int age = 25;double price = 19.99;char grade = 'A';bool isActive = true;std::cout << "Age: " << age << std::endl;std::cout << "Price: " << price << std::endl;std::cout << "Grade: " << grade << std::endl;std::cout << "Active: " << isActive << std::endl;age = 26;std::cout << "New Age: " << age << std::endl;return 0;}
Breakdown
1
int age = 25;
Declares an integer variable named 'age' and initializes it with value 25
2
double price = 19.99;
Declares a double variable for decimal numbers like prices
3
char grade = 'A';
Declares a char variable for single character values enclosed in single quotes
4
bool isActive = true;
Declares a boolean that can only be true (1) or false (0)
5
age = 26;
Reassigns the age variable to a new value, overwriting the original