CurriculumData Types

Data Types

C++ requires you to explicitly declare the type of every variable. This allows the compiler to allocate the exact amount of memory needed and optimize performance. In this deep dive, we'll explore basic types, memory sizes, what happens when you exceed limits, and how to convert between types.

01The Core Types

Here are the fundamental types in C++.

• int (Integer)
• double (Double-precision float)
• float (Single-precision float, needs 'f' suffix)
• char (Single character, single quotes)
• bool (True/False)

Run this code to see them in memory.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer

Click Run to see memory state

02Sizes of Data Types

How much RAM does a variable actually take? C++ provides the sizeof() operator to tell you exactly how many bytes a type uses on your specific machine.

(1 byte = 8 bits. So a 4-byte int has 32 bits of space).
main.cpp
Loading...
Terminal
Waiting for execution...

03Integer Overflow

What happens if you try to store a number larger than the type can hold? A standard 32-bit signed int maxes out at 2,147,483,647.

If you add 1 to it, it overflows and wraps around to the lowest negative number! Run the code to see this dangerous bug in action.
main.cpp
Loading...
Terminal
Waiting for execution...

04Type Casting (Conversion)

Sometimes you need to convert one type to another.

• Implicit Cast: C++ does it automatically (e.g., int to double), but it can be dangerous (e.g., double to int truncates the decimal).
• Explicit Cast: Using static_cast<type>(value) explicitly tells the compiler you know what you are doing.
main.cpp
Loading...
Terminal
Waiting for execution...

05The 'auto' Keyword

Since C++11, you can use the auto keyword to let the compiler figure out the type automatically based on the value you assign to it.

This is very useful for long, complex types, but don't overuse it if it makes the code hard to read for humans.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer

Click Run to see memory state

← Back to Curriculum