Variables and Types in C++
Last updated: Sat Apr 26 2025
In C++, variables are used to store data, and types define what kind of data a variable can hold. Understanding variables and types is fundamental to writing correct and efficient C++ programs.
Basic Data Types
- int: Integer numbers (e.g.,
int count = 10;) - float, double: Floating-point numbers for decimals (e.g.,
float price = 99.99f;) - char: Single character (e.g.,
char grade = 'A';) - bool: Boolean values (
trueorfalse)
Variable Declaration and Initialization
Variables must be declared with a type before they can be used:
int age = 25;
float height = 5.9f;
Uninitialized variables may contain garbage values — always initialize them.
Type Safety and Auto Keyword
C++ is a strongly-typed language. Incorrect type usage can lead to compilation errors or undefined behavior.
You can use auto to let the compiler deduce the type:
auto score = 92; // score is deduced to be an int
Best Practices
Always initialize variables.
Use meaningful variable names.
Prefer auto when the type is obvious or verbose (especially with iterators).