HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Variables

Variables

int, double, string, bool types; type deduction with auto, and const constants.

Simple enough for a 5-year-old to understand

Typed variables

Example code
1
#include <iostream>
2
#include <string>
For strings.
ImportFor strings.
3
using namespace std;
4
int main() {
5
int age = 36;
6
double height = 1.72;
7
string name = "Alex";
8
cout << name << " " << age << " " << height << endl;
Alex 36 1.72
Output / InputAlex 36 1.72
9
return 0;
10
}
ImportOutput / Input
💡 Hint: Include #include <string> to use strings.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Define and print string city = "Mersin".

🎯 Expected output: Mersin

Loading editor…

About this topic

Variables in C++ are defined with a type, and the type is fixed at compile time. Same as C up to this point. What C++ adds is the `auto` keyword: it deduces the type from the initial value itself. This is not dynamic typing, it is merely a shorthand for typing.

C++ also introduced brace initialization. This format has a major advantage: it rejects narrowing conversions. When you try to assign a floating-point value to an integer variable, it is silently accepted with the equals sign, but you get a compilation error with braces.

The danger inherited from C applies here too: an uninitialized local variable is not zero, it contains leftover values in memory. C++ doesn't protect you from this either, but defining with empty braces zeroes out the variable.

What you will learn

  • Variable definition and type deduction with `auto`
  • Why brace initialization is safer
  • The difference between `const` and `constexpr`
  • The danger of uninitialized variables

When to use?

`auto` improves readability where the type is long and obvious: such as iterator types and template returns. Where the type is short and informative, it is better to write it explicitly.

`constexpr` is used for constants known at compile time; the compiler computes the value and makes it usable in places like array sizes.

Common mistakes

Wrong

#include <iostream>
using namespace std;

int main() {
    int count;
    count++;
    cout << count << endl;
    return 0;
}

`count` was not initialized; it contains a random value from memory and the increment result is unpredictable. The program may print a different number on every run. When the compiler warning option is enabled, it gives the warning "'count' is used uninitialized", but compilation doesn't stop.

Correct

#include <iostream>
using namespace std;

int main() {
    int count = 0;
    count++;
    cout << count << endl;
    return 0;
}

Wrong

#include <iostream>
using namespace std;

int main() {
    int total = 3.7;
    cout << total << endl;
    return 0;
}

With equals assignment, the decimal part is silently dropped and `3` is printed to the screen; there is no error message. Brace initialization rejects this conversion and gives a "narrowing conversion" error. Catching data loss at compile time is better than hunting for it at runtime.

Correct

#include <iostream>
using namespace std;

int main() {
    double total{3.7};
    cout << total << endl;
    return 0;
}

Wrong

#include <iostream>
using namespace std;

int main() {
    auto value;
    value = 10;
    cout << value << endl;
    return 0;
}

`auto` deduces the type from the initial value; it cannot be used without providing a value. The compiler gives the error "declaration of 'auto value' has no initializer". `auto` is not a variable whose type is determined later; it is merely a shortcut that saves you from typing.

Correct

#include <iostream>
using namespace std;

int main() {
    auto value = 10;
    cout << value << endl;
    return 0;
}

Frequently asked questions

Does using `auto` slow down the code?

No. Type deduction happens entirely at compile time; the generated machine code is identical to as if you had written the type by hand. It has zero runtime cost. The debate is solely about readability, not performance.

What is the difference between `const` and `constexpr`?

`const` means "this variable will not change"; the value can be determined at runtime. `constexpr`, on the other hand, means "this value is known at compile time". Only `constexpr` can be used as an array size or template parameter.

Where should I define the variable?

At the point closest to where it is first used. This shortens the distance between definition and usage and narrows the lifespan of the variable. Grouping them at the beginning of the block was an old requirement of C, completely unnecessary in C++.

Summary

Types are fixed at compile time; `auto` does not change this, it only shortens the typing.

Brace initialization rejects conversions that lead to data loss.

Local variables are not automatically zeroed.

`constexpr` is a compile-time constant, `const` only declares immutability.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code