19% complete
C++ Variables and Data Types
Variables are fundamental to any programming language. They allow you to store and manipulate data in your programs. In this tutorial, you'll learn about different data types in C++ and how to use variables effectively.
What is a Variable?
A variable is a named storage location in computer memory that holds a value. Think of it as a container that stores data that can be changed during program execution. In C++, every variable has:
- A name (identifier) that you use to refer to it
- A type that determines what kind of data it can store
- A value that can change during program execution
Declaring Variables in C++
Before you can use a variable in C++, you need to declare it. The basic syntax is:
1dataType variableName; // Declaration2dataType variableName = initialValue; // Declaration with initialization
Here's an example:
1#include <iostream>23int main() {4 // Variable declaration5 int age;67 // Variable initialization8 age = 25;910 // Declaration and initialization in one step11 double height = 5.9;1213 // Displaying variables14 std::cout << "Age: " << age << " years" << std::endl;15 std::cout << "Height: " << height << " feet" << std::endl;1617 return 0;18}
Variable Naming Rules
- Variable names can contain letters, digits, and underscores
- Variable names must start with a letter or underscore
- Variable names are case-sensitive (
age
,Age
, andAGE
are different variables) - Variable names cannot use C++ keywords (like
int
,for
,while
, etc.)
Basic Data Types in C++
C++ has several built-in data types to handle different kinds of values:
Data Type | Description | Size (typical) | Example |
---|---|---|---|
int | Integer (whole number) | 4 bytes | int age = 25; |
float | Floating-point number (single precision) | 4 bytes | float price = 19.99f; |
double | Floating-point number (double precision) | 8 bytes | double pi = 3.14159; |
char | Single character | 1 byte | char grade = 'A'; |
bool | Boolean (true/false) | 1 byte | bool isActive = true; |
Example: Using Different Data Types
1#include <iostream>23int main() {4 // Integer type5 int studentCount = 30;67 // Floating-point types8 float temperature = 98.6f; // 'f' suffix for float literals9 double preciseValue = 3.14159265359;1011 // Character type12 char initial = 'J';1314 // Boolean type15 bool isPassed = true;1617 // Displaying values18 std::cout << "Number of students: " << studentCount << std::endl;19 std::cout << "Temperature: " << temperature << " F" << std::endl;20 std::cout << "Pi (precise): " << preciseValue << std::endl;21 std::cout << "Initial: " << initial << std::endl;22 std::cout << "Passed: " << isPassed << std::endl; // Displays 1 for true, 0 for false2324 return 0;25}
Type Modifiers
C++ allows you to modify the basic data types using type modifiers:
Modifier | Description | Example |
---|---|---|
signed | Can store both positive and negative values (default for most types) | signed int x = -10; |
unsigned | Can only store positive values (0 and above) | unsigned int count = 100; |
short | Reduces the size of the data type | short int smallNumber = 32767; |
long | Increases the size of the data type | long int bigNumber = 2147483647; |
long long | Even larger integer type (C++11) | long long int veryBigNumber = 9223372036854775807; |
1#include <iostream>23int main() {4 // Type modifiers in action5 unsigned int positiveOnly = 3000000000; // Would overflow in a regular int6 long double veryPrecise = 3.14159265358979323846L; // 'L' suffix for long double78 // Size of different types9 std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;10 std::cout << "Size of unsigned int: " << sizeof(unsigned int) << " bytes" << std::endl;11 std::cout << "Size of long int: " << sizeof(long int) << " bytes" << std::endl;12 std::cout << "Size of long long int: " << sizeof(long long int) << " bytes" << std::endl;1314 return 0;15}
Note:
The actual size of data types may vary depending on the compiler and platform. The sizeof
operator can be used to determine the exact size of a type on your system.
Derived Data Types
1. Arrays
An array is a collection of elements of the same type stored in contiguous memory locations.
1#include <iostream>23int main() {4 // Declaring and initializing an array5 int scores[5] = {95, 88, 76, 90, 82};67 // Accessing array elements (indexing starts at 0)8 std::cout << "First score: " << scores[0] << std::endl;9 std::cout << "Third score: " << scores[2] << std::endl;1011 // Modifying an array element12 scores[1] = 92;13 std::cout << "Updated second score: " << scores[1] << std::endl;1415 return 0;16}
2. Strings
In C++, you can work with strings in two ways:
- C-style strings (character arrays)
- The
std::string
class (from the Standard Library)
1#include <iostream>2#include <string> // Include the string header34int main() {5 // C-style string (character array)6 char greeting1[] = "Hello";78 // std::string (recommended for most cases)9 std::string greeting2 = "Hello, C++!";1011 // Displaying strings12 std::cout << greeting1 << std::endl;13 std::cout << greeting2 << std::endl;1415 // String operations with std::string16 std::string firstName = "John";17 std::string lastName = "Doe";18 std::string fullName = firstName + " " + lastName; // String concatenation1920 std::cout << "Full name: " << fullName << std::endl;21 std::cout << "Name length: " << fullName.length() << " characters" << std::endl;2223 return 0;24}
Why use std::string over C-style strings?
- Safer (no buffer overflows)
- Dynamically resizable
- Provides many useful member functions
- Easier to work with (concatenation, comparison, etc.)
3. Pointers
Pointers are variables that store memory addresses. They are a powerful feature of C++ but can be complex for beginners.
1#include <iostream>23int main() {4 // Declaring a variable5 int number = 42;67 // Declaring a pointer and initializing it with the address of 'number'8 int* ptr = &number;910 // Displaying the value and address11 std::cout << "Value of number: " << number << std::endl;12 std::cout << "Address of number: " << &number << std::endl;13 std::cout << "Value stored in ptr: " << ptr << std::endl;14 std::cout << "Value pointed to by ptr: " << *ptr << std::endl; // Dereferencing1516 // Modifying the value through the pointer17 *ptr = 100;18 std::cout << "New value of number: " << number << std::endl;1920 return 0;21}
We'll cover pointers in more detail in a future tutorial.
Constants
Constants are variables whose values cannot be changed after initialization.
1#include <iostream>23int main() {4 // Using const keyword5 const double PI = 3.14159;6 const int MAX_STUDENTS = 30;78 // This would cause a compilation error:9 // PI = 3.14; // Cannot modify a constant1011 // Using constants12 double radius = 5.0;13 double area = PI * radius * radius;1415 std::cout << "Circle area: " << area << std::endl;16 std::cout << "Maximum students: " << MAX_STUDENTS << std::endl;1718 return 0;19}
Naming Convention for Constants:
By convention, constants are often named using ALL_UPPERCASE_WITH_UNDERSCORES to distinguish them from regular variables.
Type Conversion
Sometimes you need to convert values from one data type to another. C++ supports both implicit (automatic) and explicit type conversion.
1. Implicit Type Conversion
Happens automatically when a value is assigned to a different but compatible type.
1#include <iostream>23int main() {4 int intValue = 42;5 double doubleValue = intValue; // Implicit conversion from int to double67 std::cout << "Int value: " << intValue << std::endl;8 std::cout << "Double value: " << doubleValue << std::endl;910 char charValue = 65; // ASCII value for 'A'11 std::cout << "Char value: " << charValue << std::endl; // Displays 'A'1213 return 0;14}
2. Explicit Type Conversion (Casting)
When you want to force a conversion between types, you can use casting.
1#include <iostream>23int main() {4 // C-style casting (traditional)5 double pi = 3.14159;6 int roundedPi = (int)pi; // Truncates to 378 // C++ style casting (preferred)9 double e = 2.71828;10 int roundedE = static_cast<int>(e); // Truncates to 21112 std::cout << "Original pi: " << pi << std::endl;13 std::cout << "Rounded pi: " << roundedPi << std::endl;1415 std::cout << "Original e: " << e << std::endl;16 std::cout << "Rounded e: " << roundedE << std::endl;1718 // Be careful with narrowing conversions19 int largeNumber = 1000000;20 char smallType = static_cast<char>(largeNumber); // Data loss!21 std::cout << "After narrowing conversion: " << static_cast<int>(smallType) << std::endl;2223 return 0;24}
Modern C++ Casting:
C++ provides several casting operators for different scenarios:
static_cast<type>(expression)
- For "well-behaved" conversionsdynamic_cast<type>(expression)
- For safe downcasting of polymorphic objectsconst_cast<type>(expression)
- To add or remove const qualifierreinterpret_cast<type>(expression)
- For low-level reinterpreting of bit patterns
Type Inference with auto
Modern C++ (C++11 and later) allows the compiler to automatically deduce the type of a variable using the auto
keyword.
1#include <iostream>2#include <string>34int main() {5 // Let the compiler deduce the types6 auto intValue = 42; // int7 auto doubleValue = 3.14; // double8 auto charValue = 'A'; // char9 auto text = "Hello, auto!"; // const char*10 auto message = std::string("Hi"); // std::string1112 // Displaying the values13 std::cout << "Int: " << intValue << std::endl;14 std::cout << "Double: " << doubleValue << std::endl;15 std::cout << "Char: " << charValue << std::endl;16 std::cout << "Text: " << text << std::endl;17 std::cout << "Message: " << message << std::endl;1819 return 0;20}
When to use auto:
- When the type is obvious from the initialization
- With complex types that are tedious to write out
- When working with templates and generic code
However, for simple types, it's often more readable to explicitly declare the type.
Practice Exercises
Exercise 1: Variable Declaration and Initialization
Write a program that:
- Declares variables for a person's name, age, height (in meters), and whether they are a student
- Initializes these variables with appropriate values
- Displays all this information in a formatted way
Exercise 2: Type Conversion
Write a program that:
- Declares a floating-point variable with a value like 9.99
- Converts it to an integer (notice what happens to the decimal part)
- Converts the integer to a character and displays it
- Converts the integer back to a float and displays it
Summary
In this tutorial, you've learned:
- What variables are and how to declare them in C++
- The basic data types in C++ (int, float, double, char, bool)
- How to use type modifiers to change the size and behavior of data types
- Derived data types like arrays, strings, and pointers
- How to work with constants
- Implicit and explicit type conversion
- Type inference with the auto keyword
Understanding variables and data types is fundamental to programming in C++. These concepts will be used in all your future C++ programs. In the next tutorial, we'll explore control flow statements that allow you to make decisions and repeat actions in your code.
Related Tutorials
Advanced C++ Data Types
C++ provides several advanced data types that are not available in C.
1. Enums
Enums are user-defined types that consist of a set of named integer constants.
1#include <iostream>23// C++ enums with strong typing (not available in C)4enum class Color { Red, Green, Blue };5enum class Status { Active, Inactive, Pending };67int main() {8 // C++ strongly typed enums9 Color color = Color::Blue;10 Status status = Status::Active;1112 // Cannot directly compare different enum classes (type safety)13 // if (color == status) { } // Compilation error1415 // Type traits and type info (C++ feature)16 std::cout << "Type of color: " << typeid(color).name() << std::endl;1718 return 0;19}
2. Structs
Structs are user-defined types that group together related variables.
1#include <iostream>2#include <string>3#include <memory> // For smart pointers45// C++ struct with methods and access specifiers6struct Person {7private:8 std::string name;9 int age;1011public:12 // Constructor13 Person(std::string n, int a) : name(n), age(a) {}1415 // Methods within struct (not possible in C)16 void display() const {17 std::cout << "Name: " << name << ", Age: " << age << std::endl;18 }1920 void birthday() {21 age++;22 std::cout << name << " is now " << age << " years old." << std::endl;23 }24};2526int main() {27 // Modern C++ smart pointers (not in C)28 std::unique_ptr<Person> person = std::make_unique<Person>("Alice", 25);29 person->display();30 person->birthday();3132 return 0;33}
3. Smart Pointers
Smart pointers are objects that manage the lifetime of dynamically allocated objects.
1#include <iostream>2#include <memory> // For smart pointers34int main() {5 // Modern C++ smart pointers (not in C)6 std::unique_ptr<int> ptr = std::make_unique<int>(42);78 // Displaying the value9 std::cout << "Value: " << *ptr << std::endl;1011 return 0;12}
4. Type Traits
Type traits are templates that provide compile-time information about types.
1#include <iostream>23int main() {4 // Type traits example5 int value = 42;6 std::cout << "Is value a pointer: " << std::is_pointer<decltype(value)>::value << std::endl;7 std::cout << "Is value a const: " << std::is_const<decltype(value)>::value << std::endl;89 return 0;10}
Summary
In this tutorial, you've learned:
- Advanced C++ data types like enums, structs, and smart pointers
- Type traits and compile-time information about types
Understanding advanced data types is important for writing efficient and robust C++ programs. These concepts will be used in all your future C++ programs. In the next tutorial, we'll explore control flow statements that allow you to make decisions and repeat actions in your code.