Definition
📌 Variables
Just like C, C++ variables must have a declared type.
Syntax
syntax
type variableName = value;
auto variableName = value; // type inferredExample
cpp
#include <iostream>
using namespace std;
int main() {
int age = 20;
auto price = 49.99; // inferred as double
cout << "Age: " << age << endl;
cout << "Price: " << price << endl;
return 0;
}Output
outputAge: 20
Price: 49.99
Important Points
- C++ variables need a type just like in C —
int,double,char, etc. autoinfers the type from the assigned value at declaration.- Variables must be initialized before meaningful use — uninitialized locals hold garbage.
constbefore a type makes a variable read-only after initialization.
Common Mistakes
- Using
autowithout an initializer — the compiler has nothing to infer from. - Shadowing an outer-scope variable name inside a nested block by mistake.
- Assuming
constvariables can be changed later — they can't.
Interview Tip
🎯 Before your interview
Know when NOT to use
auto — for readability, explicit types are often clearer for public function signatures.
