Data Types and Variables in C++
In C++, data types and variables form the core of any program, as they define the kind of data you can work with and how you store it. Different data types allow you to handle numbers, text, and more complex types in various ways.
Primitive Data Types
Primitive data types are the basic types of data built into C++. Here are some of the most commonly used ones:
- int: Used to store integers (whole numbers). Example:
int age = 25;
- float: Used to store single-precision decimal numbers. Example:
float temperature = 37.5;
- double: Used for double-precision decimal numbers (more accurate than float). Example:
double pi = 3.14159;
- char: Stores a single character. Example:
char grade = 'A';
- bool: Stores
true
orfalse
values. Example:bool isRainy = true;
Real-Life Example: Let’s consider a simple program that uses some of these data types to display information about a car.
Variables and Constants
- Variables are named storage for values that can change during the program.
- Constants are values that, once defined, cannot be altered throughout the program.
In C++, constants are declared using the const
keyword. For example:
pi
is a constant because the value of π doesn’t change, whereas radius
is a variable that can be set by the user.Type Modifiers
Type modifiers alter the size or range of data types. Common type modifiers in C++ are:
- signed: The default modifier, allowing both positive and negative values.
- unsigned: Allows only non-negative values but doubles the maximum value range.
- short and long: Modifiers that decrease or increase the storage size.
Example: Suppose you’re storing an employee’s ID and age.
In this example, we use unsigned
for employeeID
since an ID should only be positive, while age
is signed
to allow for a negative value if the age is unknown or unassigned.
Type Casting
Type casting converts one data type to another, which can be useful in calculations and specific cases where data types need to be matched.
Two common types of casting are:
- Implicit casting: Done automatically by C++ when assigning compatible types.
- Explicit casting: Done manually using casting operators, like
static_cast
, to convert between data types safely.
Real-Life Example: Suppose you want to calculate the average score of a student, and the scores are integers, but the average should be a floating-point number.
static_cast<float>
ensures that the integer sum is cast to a floating-point number, allowing us to get an accurate decimal result for the average score.