Curriculum / C++ / Lesson 02

Variables in C++

Just like C, C++ variables must have a declared type.

2 of 10
beginner 📖 4 min read 🎯 1 question

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 inferred

Example

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.

Quick Quiz

1. What does the 'auto' keyword do in C++?

Back to curriculum