C++ Data Types and Variables | Built-in Types, Constants, sizeof and Type Casting
This complete tutorial on C++ Data Types and Variables explains how data is stored and managed in C++ programs. It covers built-in data types, type modifiers, the sizeof operator, constants using const and constexpr, and both implicit and explicit type casting. The tutorial follows best coding practices and helps beginners write safe, efficient, and readable C++ programs.
Data Types and Variables – Complete Tutorial
1. Variables in C++
A variable is a named memory location used to store data. The type of variable determines what kind of data it can hold.
Syntax:
Example:
Best Practices:
- Use meaningful variable names
- Initialize variables at the time of declaration
- Avoid unnecessary global variables
2. Built-in Data Types
C++ provides several built-in data types.
Fundamental Data Types:
| Data TypeDescriptionExample | ||
int | Integer numbers | int x = 10; |
float | Decimal numbers | float pi = 3.14; |
double | Double precision decimal | double d = 3.14159; |
char | Single character | char c = 'A'; |
bool | True or false | bool flag = true; |
void | No value | Used in functions |
3. Type Modifiers
Type modifiers change the size or range of built-in data types.
Common Type Modifiers:
shortlongsignedunsigned
Example:
Note:
unsignedtypes store only positive values- Size of data types may vary by system and compiler
4. sizeof Operator
The sizeof operator is used to find the size (in bytes) of a data type or variable.
Example:
Using with variables:
Best Practices:
- Use
sizeofinstead of assuming data type sizes - Useful for memory optimization and portability
5. Constants in C++
Constants are variables whose values cannot be changed after initialization.
Using const
Using constexpr
Difference Between const and constexpr:
| Featureconstconstexpr | ||
| Evaluated | Runtime | Compile time |
| Use case | Fixed values | Compile-time constants |
| Performance | Normal | Optimized |
Best Practices:
- Prefer
constexprfor compile-time values - Use
constto protect variables from modification
6. Type Casting
Type casting is the process of converting one data type into another.
6.1 Implicit Type Casting
Done automatically by the compiler.
Example:
6.2 Explicit Type Casting
Done manually by the programmer.
Example:
Modern C++ style:
Best Practices:
- Avoid unnecessary type casting
- Prefer
static_castover C-style casting - Be careful of data loss during casting
Common Mistakes to Avoid
- Using uninitialized variables
- Ignoring data type limits
- Mixing signed and unsigned types
- Overusing type casting
Summary
In this chapter, you learned about C++ data types and variables, built-in data types, type modifiers, the sizeof operator, constants, and type casting. Understanding these concepts is essential for writing correct and efficient C++ programs.