Variables
Just like C, C++ variables must have a declared type. C++ additionally offers the auto keyword, which lets the compiler infer a variable's type from its initial value — useful for keeping code concise.
💡 Key insight
auto doesn't make C++ dynamically typed — the type is still fixed at compile time, just inferred for you.
Syntax
syntax
type variableName = value;
auto variableName = value; // type inferredExample
The compiler infers price as a double because 49.99 is a decimal literal.
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;
}outputAge: 20
Price: 49.99
Try it yourself
Copy this example into the C++ compiler and run it — try changing a value and see what happens.
