cpp / beginner
Snippet
Declaring and Using Variables
Variables are containers for storing data values. In C++, you must declare the type of a variable before using it. The four fundamental variable types shown here are: int for whole numbers, double for decimal numbers, char for single characters, and bool for true/false values. Each variable is initialized with a specific value using the assignment operator (=).
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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: " << std::boolalpha << isActive << std::endl;return 0;}
Breakdown
1
#include <iostream>
Includes the input/output stream library for std::cout
2
int main() {
Main function where program execution begins
3
int age = 25;
Declares an integer variable named age with value 25
4
double price = 19.99;
Declares a double variable for decimal numbers
5
char grade = 'A';
Declares a character variable holding a single character
6
bool isActive = true;
Declares a boolean that can only be true or false
7
std::cout << "Age: " << age << std::endl;
Prints text and the variable value to the console
8
std::boolalpha << isActive
Formats boolean output as 'true' or 'false' words