Learn C++
#include "variablesdatatypes/variables.hpp"

Variables in C++

//concept

A variable in C++ is a named slot of memory with a fixed type decided at declaration — int score = 0; reserves integer storage and binds the name score to it. Unlike Python, the type can never change afterward: assigning a string to an int variable is a compile error, not a runtime surprise.

Declaration and initialization are separate ideas worth keeping distinct. int x; declares without a value (built-in types are left with indeterminate garbage, not zero), while int x = 5;, int x{5};, and int x(5) all initialize immediately — and initializing immediately is the habit that prevents a whole class of bugs.

//how it works
1

Declaration fixes the type

int score; tells the compiler score will always be an int. Its type is locked in for the rest of its scope.

2

Uninitialized means garbage

Built-in types declared without a value hold whatever bits were in that memory — reading them is undefined behavior, not a clean zero.

3

Prefer immediate initialization

int score = 0; (copy), int score{0}; (braces, rejects narrowing), and int score(0); all start life with a known value.

4

Braced init blocks narrowing

int x{3.99}; refuses to compile because it would silently drop .99, while int x = 3.99; compiles with a warning — braces are the safer default.

//example
#include <iostream>
 
int main() {
int score{0};
score = 42;
std::cout << "score=" << score << std::endl;
return 0;
}
Output
score=42
1int score{0}; declares an int and initializes it to 0 in one step — no garbage, no narrowing risk.
2score = 42; reassigns the same memory slot; the type stays int throughout.
3The output confirms the variable holds 42 at print time.
//use cases
Always initializing locals to dodge undefined-behavior bugs from garbage values
Choosing braced initialization in new code to let the compiler reject narrowing conversions
Reading legacy code that mixes = , (), and {} initialization styles
Explaining to a Python convert why x = "hi" after int x fails at compile time

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.