Chapter 04 of 48

Variables & Data Types

Every program works with data: a student's marks, a price, a name, whether a test passed. To work with data, a program must store it somewhere in memory and remember what kind of data it is. In C++, we do this with variables, and every variable has a data type.

In this chapter we will learn how to create and initialise variables, all the built-in data types, how much memory they take, what values they can hold, and some surprising traps (overflow, floating-point rounding, uninitialised variables) that interviewers love to ask about.


What is a Variable?

A variable is a named piece of memory that holds a value of a specific type. The value can change while the program runs.

Think of memory as a long row of numbered boxes (bytes). A variable gives a name to a few of those boxes and tells the compiler what kind of value lives there:

int age = 20;

  name   →  age
  type   →  int (4 bytes on most systems)
  value  →  20
  memory →  ┌────┬────┬────┬────┐
            │      20 (4 bytes)  │   at some address, e.g. 0x7ffd5e8c
            └────┴────┴────┴────┘

The type decides three things:

  1. how many bytes the variable uses,

  2. which values it can hold (its range), and

  3. which operations are allowed on it (you can divide two ints, but not two bools in a meaningful way).

Here is a first example with the most common types:

#include <iostream>
#include <string>

int main() {
    int age = 20;              // whole number
    double cgpa = 8.75;        // number with a fractional part
    char grade = 'A';          // a single character
    bool passed = true;        // true or false
    std::string name = "Neha"; // text (a library type, not a built-in one)

    std::cout << name << " is " << age << " years old\n";
    std::cout << "CGPA: " << cgpa << ", Grade: " << grade << '\n';
    std::cout << "Passed: " << passed << '\n';

    age = 21;                  // a variable's value can change
    std::cout << "Next year: " << age << '\n';
}

Output:

Neha is 20 years old
CGPA: 8.75, Grade: A
Passed: 1
Next year: 21

Notice that bool printed as 1. We will see how to print true instead in a moment.


Declaring and Initialising Variables

The general form is:

type name;              // declaration (definition) without an initial value
type name = value;      // definition with initialisation
type a = 1, b = 2;      // several variables of the same type

C++ has several ways to give a variable its starting value:

#include <iostream>

int main() {
    int a = 10;     // copy initialisation (C style)
    int b(20);      // direct initialisation
    int c{30};      // brace (list) initialisation, C++11
    int d = {40};   // copy-list initialisation, C++11
    int e{};        // empty braces: value-initialised to 0

    std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << '\n';

    int x = 7.9;    // compiles: silently truncated to 7
    std::cout << "x = " << x << '\n';
}

Output:

10 20 30 40 0
x = 7
SyntaxNameSince
int a = 10;Copy initialisationC++98
int b(20);Direct initialisationC++98
int c{30};Direct-list (brace) initialisationC++11
int d = {40};Copy-list initialisationC++11
int e{};Value initialisation (gives 0)C++11

Why brace initialisation is safer

Look again at int x = 7.9;. It compiled without even a warning under -Wall -Wextra, and x silently became 7. Brace initialisation does not allow such a narrowing conversion (a conversion that can lose information):

int main() {
    int y{7.9};     // error: narrowing conversion
    return y;
}
main.cpp: In function ‘int main()’:
main.cpp:2:11: error: narrowing conversion of ‘7.9000000000000004e+0’ from ‘double’ to ‘int’ [-Wnarrowing]
    2 |     int y{7.9};     // error: narrowing conversion
      |           ^~~

That is why many modern C++ style guides prefer {}. (If you want the compiler to warn about int x = 7.9; as well, add the -Wconversion flag.) The full rules of conversions are in the chapter Type Conversion & Casting.


Naming Rules (Identifiers)

A variable's name is an identifier. The rules are:

  • It may contain letters, digits and the underscore _.

  • It must not start with a digit: 2ndRank is invalid, rank2 is fine.

  • It must not be a keyword such as int, class, new, delete, return, this, true.

  • It is case-sensitive: marks, Marks and MARKS are three different names.

  • No spaces or symbols like -, @, $: total-marks means "total minus marks".

  • Names that begin with an underscore followed by a capital letter (_Value) or that contain a double underscore (my__var) are reserved for the compiler and library. Avoid them.

NameValid?Reason
totalMarksYescamelCase, common style
total_marksYessnake_case, the style of the standard library
_countYes (but avoid at global scope)Leading underscore names are reserved in the global namespace
2ndYearNoStarts with a digit
floatNoKeyword
roll noNoContains a space

Choose meaningful names: attendancePercent is much better than ap or x.


Fundamental Data Types

C++ has a small set of fundamental (built-in) types. Everything else, such as std::string, std::vector or your own classes, is built from them.

                       Fundamental types
                              │
      ┌───────────────┬───────┴────────┬──────────────┐
      │               │                │              │
   Integer        Floating-point      bool          void
      │           float, double,    (true/false)  (no value)
      │           long double
      │
 ┌────┴──────────────────────┐
 │                           │
Character types         Signed / unsigned integers
char, signed char,      short, int, long, long long
unsigned char,          (and their unsigned versions)
wchar_t, char8_t,
char16_t, char32_t

Strictly speaking, the standard counts bool and the character types as integral types too (they all store whole numbers); the diagram separates them only because we use them differently. There is also std::nullptr_t, the type of nullptr, which we meet in Constants & Literals.

Sizes are not fixed by the standard

This surprises many students: the C++ standard does not say that int is 4 bytes. It only gives minimum sizes and an ordering:

1 == sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long) ≤ sizeof(long long)

short     : at least 16 bits
int       : at least 16 bits
long      : at least 32 bits
long long : at least 64 bits  (C++11)

The actual sizes depend on the platform. The sizeof operator tells you the size in bytes:

#include <iostream>

int main() {
    std::cout << "bool        : " << sizeof(bool) << " byte(s)\n";
    std::cout << "char        : " << sizeof(char) << '\n';
    std::cout << "short       : " << sizeof(short) << '\n';
    std::cout << "int         : " << sizeof(int) << '\n';
    std::cout << "long        : " << sizeof(long) << '\n';
    std::cout << "long long   : " << sizeof(long long) << '\n';
    std::cout << "float       : " << sizeof(float) << '\n';
    std::cout << "double      : " << sizeof(double) << '\n';
    std::cout << "long double : " << sizeof(long double) << '\n';
    std::cout << "wchar_t     : " << sizeof(wchar_t) << '\n';
    std::cout << "char8_t     : " << sizeof(char8_t) << '\n';
    std::cout << "char16_t    : " << sizeof(char16_t) << '\n';
    std::cout << "char32_t    : " << sizeof(char32_t) << '\n';
}

Output on 64-bit Linux with g++ 15:

bool        : 1 byte(s)
char        : 1
short       : 2
int         : 4
long        : 8
long long   : 8
float       : 4
double      : 8
long double : 16
wchar_t     : 4
char8_t     : 1
char16_t    : 2
char32_t    : 4

On 64-bit Windows, a few results differ: long is 4 bytes (Windows uses the "LLP64" model, Linux and macOS use "LP64"), wchar_t is 2 bytes, and with MSVC long double is 8 bytes (the same as double). This is why portable code never assumes the size of long.

The full table (typical 64-bit Linux)

TypeTypical sizeTypical range / precisionUse for
bool1 bytetrue or falseYes/no conditions
char1 byte-128 to 127 or 0 to 255 (platform-dependent)A single character
signed char / unsigned char1 byte-128 to 127 / 0 to 255Small numbers, raw bytes
short2 bytes-32,768 to 32,767Rarely needed
int4 bytes-2,147,483,648 to 2,147,483,647 (about ±2.1 × 109)The default integer type
unsigned int4 bytes0 to 4,294,967,295Non-negative values, bit patterns
long8 bytes (4 on Windows)Same as long long on LinuxAvoid in portable code
long long8 bytesabout ±9.22 × 1018Large counts, sums, products
float4 bytesabout 6-7 significant digitsGraphics, memory-tight arrays
double8 bytesabout 15-16 significant digitsThe default for decimals
long double16 bytes on x86-64 Linux (8 with MSVC)at least as precise as doubleExtra precision when available
wchar_t4 bytes (2 on Windows)Wide charactersWindows APIs
char8_t (C++20)1 byteUTF-8 code unitsUTF-8 text
char16_t / char32_t (C++11)2 / 4 bytesUTF-16 / UTF-32 code unitsUnicode text
void(none)No valuesFunctions that return nothing

Since C++20, signed integers are guaranteed to use two's complement representation, so an N-bit signed integer always has the range -2N-1 to 2N-1 - 1. Before C++20, other representations were technically allowed.

Exact limits with <limits>

Instead of memorising ranges, ask the compiler with std::numeric_limits:

#include <iostream>
#include <limits>

int main() {
    std::cout << "int min      : " << std::numeric_limits<int>::min() << '\n';
    std::cout << "int max      : " << std::numeric_limits<int>::max() << '\n';
    std::cout << "unsigned max : " << std::numeric_limits<unsigned int>::max() << '\n';
    std::cout << "long long max: " << std::numeric_limits<long long>::max() << '\n';
    std::cout << "double max   : " << std::numeric_limits<double>::max() << '\n';
    std::cout << "double digits: " << std::numeric_limits<double>::digits10 << '\n';
    std::cout << "float digits : " << std::numeric_limits<float>::digits10 << '\n';
}

Output:

int min      : -2147483648
int max      : 2147483647
unsigned max : 4294967295
long long max: 9223372036854775807
double max   : 1.79769e+308
double digits: 15
float digits : 6

digits10 is the number of decimal digits the type can store without change: 15 for double and only 6 for float.

A handy rule for competitive programming: an int holds values up to about 2 × 109, and a long long up to about 9 × 1018. If a sum or product can exceed 2 × 109 (for example, multiplying two numbers up to 105), use long long.


Integer Types in Detail

Signed vs unsigned

Adding unsigned removes negative values and doubles the positive range. signed is the default for short, int, long and long long, so int and signed int are the same type. Also, short is short for short int, long for long int, and unsigned alone means unsigned int.

Overflow: unsigned wraps, signed is undefined

What happens when a value goes past the end of its range? The answer is different for unsigned and signed types, and this is a classic interview question.

Unsigned arithmetic is always done modulo 2N, so it "wraps around" in a well-defined way:

#include <iostream>
#include <limits>

int main() {
    unsigned int u = 0;
    u = u - 1;                         // well defined: wraps around
    std::cout << "0u - 1 = " << u << '\n';

    unsigned int big = std::numeric_limits<unsigned int>::max();
    big = big + 1;                     // wraps to 0
    std::cout << "max + 1 = " << big << '\n';
}

Output:

0u - 1 = 4294967295
max + 1 = 0
unsigned int (32 bits) is like a clock with 2^32 positions:

   ... 4294967294 → 4294967295 → 0 → 1 → 2 ...
                         ▲          │
                         └── wraps ─┘

Signed overflow is undefined behavior (UB). The C++ standard places no requirements at all on what happens: the program may print a "wrapped" number, give a different answer when optimised, or behave strangely elsewhere. Compilers actually rely on "signed overflow never happens" when optimising.

#include <iostream>
#include <limits>

int main() {
    int n = std::numeric_limits<int>::max();
    n = n + 1;                         // undefined behavior!
    std::cout << n << '\n';
}

Built normally, this printed -2147483648 on our machine, but that is just one possible result, not a guarantee. Compile with the Undefined Behavior Sanitizer (-fsanitize=address,undefined) and the bug is reported:

main.cpp:6:7: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648

So: never rely on signed overflow. Use a larger type (long long), or check before adding.

Fixed-width integers: <cstdint> (C++11)

When you need an exact size (file formats, network protocols, hashing), use the types from <cstdint>: std::int8_t, std::int16_t, std::int32_t, std::int64_t and their unsigned versions std::uint8_t ... std::uint64_t.

#include <cstdint>
#include <iostream>

int main() {
    std::int8_t   tiny  = 100;
    std::int32_t  rollNo = 2'024'001;
    std::uint64_t views = 18'000'000'000ULL;

    std::cout << sizeof(tiny) << ' ' << sizeof(rollNo) << ' ' << sizeof(views) << '\n';
    std::cout << rollNo << ' ' << views << '\n';
    std::cout << tiny << '\n';                     // surprise!
    std::cout << static_cast<int>(tiny) << '\n';
}

Output:

1 4 8
2024001 18000000000
d
100

Why did tiny print d? On almost every platform, std::int8_t is just another name for signed char, and std::cout prints char types as characters. The value 100 is the character code of 'd'. Convert to int to see the number. (The ' inside 2'024'001 is a digit separator, explained in Constants & Literals.)

You will also meet std::size_t: an unsigned type that can hold the size of any object. It is the type returned by sizeof and by .size() of standard containers.


Character Type: char

A char stores one character, written in single quotes. Internally it stores a small integer code (on almost all systems, the ASCII code for basic English characters):

#include <iostream>

int main() {
    char c = 'A';
    std::cout << c << '\n';                     // prints the character
    std::cout << static_cast<int>(c) << '\n';   // prints its code: 65
    char next = c + 1;
    std::cout << next << '\n';                  // B

    bool ok = true;
    std::cout << ok << ' ' << !ok << '\n';      // 1 0
    std::cout << std::boolalpha << ok << ' ' << !ok << '\n';

    bool fromInt = 42;                          // any non-zero value becomes true
    std::cout << fromInt << '\n';
}

Output:

A
65
B
1 0
true false
true

Key points:

  • 'A' is 65, 'a' is 97 and '0' is 48 in ASCII. Because codes for '0' to '9' are consecutive (this is guaranteed by the standard), ch - '0' converts a digit character into its number.

  • Whether plain char is signed or unsigned depends on the platform (signed on x86, unsigned on ARM Linux). char, signed char and unsigned char are three distinct types.

  • A char holds one byte, not one "letter" of every language. Text like "नमस्ते" needs several bytes per character in UTF-8. For text, use std::string (see Strings).


Boolean Type: bool

A bool holds true or false. It is the result of comparisons like marks >= 40.

  • By default std::cout prints 1 and 0; after std::boolalpha it prints true and false (as in the output above).

  • Converting a number to bool: zero becomes false, any non-zero value becomes true. That is why bool fromInt = 42; printed true.

  • Converting bool to a number: true becomes 1, false becomes 0.


Floating-Point Types: float and double

Floating-point types store numbers with a fractional part, such as 8.75 or 3.14159. On practically every modern system they follow the IEEE 754 standard: float is 32-bit single precision and double is 64-bit double precision.

They store numbers in binary, and many simple decimal numbers like 0.1 cannot be represented exactly in binary (just as 1/3 cannot be written exactly in decimal). So small rounding errors appear:

#include <iomanip>
#include <iostream>

int main() {
    double a = 0.1 + 0.2;
    std::cout << a << '\n';                              // default: 6 significant digits
    std::cout << std::setprecision(17) << a << '\n';     // the real stored value
    std::cout << std::boolalpha << (a == 0.3) << '\n';

    float f = 16777216.0f;      // 2^24
    float g = f + 1.0f;         // float cannot represent 16777217
    std::cout << std::setprecision(10) << f << ' ' << g << '\n';
}

Output:

0.3
0.30000000000000004
false
16777216 16777216

Three lessons from this output:

  1. std::cout shows only 6 significant digits by default, so 0.30000000000000004 looks like 0.3.

  2. Never compare floating-point numbers with ==. Compare with a small tolerance instead: std::abs(a - b) < 1e-9 (with <cmath>).

  3. float has only a 24-bit significand, so above 224 = 16,777,216 it cannot even represent every whole number: adding 1 changed nothing. Prefer double unless you have a specific reason to use float. And never use floating point for money; store paise as integers instead.


Letting the Compiler Choose: auto (C++11)

With auto, the compiler deduces the variable's type from its initialiser. The type is still fixed at compile time; auto does not make C++ dynamically typed.

#include <iostream>
#include <string>
#include <typeinfo>

int main() {
    auto a = 10;        // int
    auto b = 2.5;       // double
    auto c = 'x';       // char
    auto d = 10 / 4;    // int (integer division!)
    auto e = 10 / 4.0;  // double

    std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << '\n';
    std::cout << sizeof(a) << ' ' << sizeof(b) << ' ' << sizeof(c) << '\n';
}

Output:

10 2.5 x 2 2.5
4 8 1

Notice d: 10 / 4 is integer division, so d is an int with value 2. auto takes the type of the expression exactly as it is; it does not guess what you meant. An auto variable must be initialised (auto x; is an error), because there is nothing to deduce from.

auto is most useful for long type names, such as iterators (auto it = myMap.begin();), which you will see in the STL chapters. For simple numbers, writing int or double is often clearer.


Uninitialised Variables

What value does a variable have if you don't give it one? It depends on where it is declared:

#include <iostream>

int counter;          // global: zero-initialised automatically

int main() {
    int local;        // local: indeterminate value
    std::cout << counter << '\n';
    std::cout << local << '\n';   // undefined behavior: reading an indeterminate value
}

Compiler output (a warning, so the program is still built):

main.cpp: In function ‘int main()’:
main.cpp:8:18: warning: ‘local’ is used uninitialized [-Wuninitialized]
    8 |     std::cout << local << '\n';   // undefined behavior: reading an indeterminate value
      |                  ^~~~~
main.cpp:6:9: note: ‘local’ was declared here
    6 |     int local;        // local: indeterminate value
      |         ^~~~~
Where the variable livesInitial value if none is given
Global or static variableZero (zero-initialised before the program starts)
Local variable of a built-in typeIndeterminate: whatever bits happened to be in that memory

In C++23, reading an indeterminate value is undefined behavior. When we ran this program it happened to print 0 for local, but it could print garbage or behave differently with other compiler options. (C++26 reclassifies this as "erroneous behavior" so compilers can diagnose it more consistently, but it is still a bug.) The fix is simple: always initialise local variables, for example int local{}; or int local = 0;.


Scope: Where a Variable Can Be Used

A variable's scope is the part of the program where its name is visible.

  • A local variable is declared inside a block { } and can be used only from its declaration to the end of that block. It is created when execution reaches the declaration and destroyed at the end of the block.

  • A global variable is declared outside all functions and is visible from its declaration to the end of the file. It lives for the whole program.

  • A local variable with the same name hides (shadows) a global one. ::name still reaches the global.

#include <iostream>

int x = 100;                    // global variable

int main() {
    int x = 5;                  // local x hides the global x
    std::cout << x << '\n';     // 5
    std::cout << ::x << '\n';   // 100: :: means "the global one"
    {
        int y = 1;              // y exists only inside this block
        std::cout << x + y << '\n';
    }
    // std::cout << y;          // error: y is not declared here
}

Output:

5
100
6

Prefer local variables. Global variables can be changed from anywhere, which makes bugs hard to track down.


Common Mistakes

  • Using a local variable before giving it a value. Undefined behavior; always initialise.

  • Integer overflow in int, for example int area = 100000 * 100000;. Use long long, and make sure the calculation itself happens in long long: 100000LL * 100000.

  • Expecting 5 / 2 to be 2.5. Two integers give an integer result. Write 5.0 / 2.

  • Comparing doubles with ==. Use a tolerance.

  • Assuming long is 8 bytes. It is 4 bytes on Windows. Use long long or std::int64_t.

  • Printing std::int8_t or std::uint8_t and getting a strange character. Cast to int first.

  • Mixing signed and unsigned, for example comparing -1 < 1u, which is false because -1 is converted to a huge unsigned value. More on this in Type Conversion & Casting.


Interview / GATE Questions

What is the size of int in C++?

The standard only guarantees at least 16 bits and sizeof(short) ≤ sizeof(int) ≤ sizeof(long). On all mainstream 32-bit and 64-bit desktop systems today it is 4 bytes (32 bits). Use sizeof(int) to check.

What is sizeof(char)?

Always exactly 1, by definition. sizeof measures sizes in units of char. (A byte in C++ has at least 8 bits; on all common systems it is exactly 8.)

What happens on unsigned overflow? On signed overflow?

Unsigned arithmetic wraps around modulo 2N, which is well defined. Signed overflow is undefined behavior: anything can happen, and optimisers assume it never occurs.

What does unsigned int x = -1; store, if unsigned int is 32 bits?

4294967295 (232 - 1). Converting a negative value to an unsigned type is well defined: the result is the value modulo 2N.

What is the default value of a local int and of a global int?

A global (or static) int is zero-initialised. A local int without an initialiser has an indeterminate value, and reading it is undefined behavior (erroneous behavior from C++26).

Why is int x{3.5}; an error but int x = 3.5; is not?

Brace (list) initialisation, introduced in C++11, forbids narrowing conversions. Copy initialisation with = allows the conversion and silently truncates to 3.

What is printed by std::cout << (0.1 + 0.2 == 0.3);?

0 (false), because 0.1, 0.2 and 0.3 cannot be stored exactly in binary floating point, and the stored sum differs slightly from the stored 0.3.

Is auto in C++ like a dynamically typed variable in Python?

No. auto only asks the compiler to deduce the type from the initialiser at compile time. After that, the variable has a fixed type, exactly as if you had written it yourself.


In Simple Words

A variable is a named, typed box in memory. The type decides its size, its range and what you can do with it. Initialise every variable, pick int/long long for whole numbers and double for decimals, and remember that unsigned overflow wraps while signed overflow is undefined.

bool        → true / false                   (1 byte)
char        → one character, really a small integer (1 byte)
int         → default integer, about ±2.1 × 10^9 (usually 4 bytes)
long long   → big integer, about ±9.2 × 10^18   (8 bytes)
double      → default decimal, ~15 digits     (8 bytes)
float       → smaller decimal, ~6 digits      (4 bytes)
auto        → type deduced from the initialiser (C++11)
int x{};    → brace init: zero value, no narrowing (C++11)

In the next chapter, Constants & Literals, we will see how to create values that can never change (const, constexpr) and all the ways of writing values directly in code.