Progress3/16 topics

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:

C++
1dataType variableName; // Declaration
2dataType variableName = initialValue; // Declaration with initialization

Here's an example:

C++
1#include <iostream>
2
3int main() {
4 // Variable declaration
5 int age;
6
7 // Variable initialization
8 age = 25;
9
10 // Declaration and initialization in one step
11 double height = 5.9;
12
13 // Displaying variables
14 std::cout << "Age: " << age << " years" << std::endl;
15 std::cout << "Height: " << height << " feet" << std::endl;
16
17 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, and AGE 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 TypeDescriptionSize (typical)Example
intInteger (whole number)4 bytesint age = 25;
floatFloating-point number (single precision)4 bytesfloat price = 19.99f;
doubleFloating-point number (double precision)8 bytesdouble pi = 3.14159;
charSingle character1 bytechar grade = 'A';
boolBoolean (true/false)1 bytebool isActive = true;

Example: Using Different Data Types

C++
1#include <iostream>
2
3int main() {
4 // Integer type
5 int studentCount = 30;
6
7 // Floating-point types
8 float temperature = 98.6f; // 'f' suffix for float literals
9 double preciseValue = 3.14159265359;
10
11 // Character type
12 char initial = 'J';
13
14 // Boolean type
15 bool isPassed = true;
16
17 // Displaying values
18 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 false
23
24 return 0;
25}

Type Modifiers

C++ allows you to modify the basic data types using type modifiers:

ModifierDescriptionExample
signedCan store both positive and negative values (default for most types)signed int x = -10;
unsignedCan only store positive values (0 and above)unsigned int count = 100;
shortReduces the size of the data typeshort int smallNumber = 32767;
longIncreases the size of the data typelong int bigNumber = 2147483647;
long longEven larger integer type (C++11)long long int veryBigNumber = 9223372036854775807;
C++
1#include <iostream>
2
3int main() {
4 // Type modifiers in action
5 unsigned int positiveOnly = 3000000000; // Would overflow in a regular int
6 long double veryPrecise = 3.14159265358979323846L; // 'L' suffix for long double
7
8 // Size of different types
9 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;
13
14 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.

C++
1#include <iostream>
2
3int main() {
4 // Declaring and initializing an array
5 int scores[5] = {95, 88, 76, 90, 82};
6
7 // 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;
10
11 // Modifying an array element
12 scores[1] = 92;
13 std::cout << "Updated second score: " << scores[1] << std::endl;
14
15 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)
C++
1#include <iostream>
2#include <string> // Include the string header
3
4int main() {
5 // C-style string (character array)
6 char greeting1[] = "Hello";
7
8 // std::string (recommended for most cases)
9 std::string greeting2 = "Hello, C++!";
10
11 // Displaying strings
12 std::cout << greeting1 << std::endl;
13 std::cout << greeting2 << std::endl;
14
15 // String operations with std::string
16 std::string firstName = "John";
17 std::string lastName = "Doe";
18 std::string fullName = firstName + " " + lastName; // String concatenation
19
20 std::cout << "Full name: " << fullName << std::endl;
21 std::cout << "Name length: " << fullName.length() << " characters" << std::endl;
22
23 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.

C++
1#include <iostream>
2
3int main() {
4 // Declaring a variable
5 int number = 42;
6
7 // Declaring a pointer and initializing it with the address of 'number'
8 int* ptr = &number;
9
10 // Displaying the value and address
11 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; // Dereferencing
15
16 // Modifying the value through the pointer
17 *ptr = 100;
18 std::cout << "New value of number: " << number << std::endl;
19
20 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.

C++
1#include <iostream>
2
3int main() {
4 // Using const keyword
5 const double PI = 3.14159;
6 const int MAX_STUDENTS = 30;
7
8 // This would cause a compilation error:
9 // PI = 3.14; // Cannot modify a constant
10
11 // Using constants
12 double radius = 5.0;
13 double area = PI * radius * radius;
14
15 std::cout << "Circle area: " << area << std::endl;
16 std::cout << "Maximum students: " << MAX_STUDENTS << std::endl;
17
18 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.

C++
1#include <iostream>
2
3int main() {
4 int intValue = 42;
5 double doubleValue = intValue; // Implicit conversion from int to double
6
7 std::cout << "Int value: " << intValue << std::endl;
8 std::cout << "Double value: " << doubleValue << std::endl;
9
10 char charValue = 65; // ASCII value for 'A'
11 std::cout << "Char value: " << charValue << std::endl; // Displays 'A'
12
13 return 0;
14}

2. Explicit Type Conversion (Casting)

When you want to force a conversion between types, you can use casting.

C++
1#include <iostream>
2
3int main() {
4 // C-style casting (traditional)
5 double pi = 3.14159;
6 int roundedPi = (int)pi; // Truncates to 3
7
8 // C++ style casting (preferred)
9 double e = 2.71828;
10 int roundedE = static_cast<int>(e); // Truncates to 2
11
12 std::cout << "Original pi: " << pi << std::endl;
13 std::cout << "Rounded pi: " << roundedPi << std::endl;
14
15 std::cout << "Original e: " << e << std::endl;
16 std::cout << "Rounded e: " << roundedE << std::endl;
17
18 // Be careful with narrowing conversions
19 int largeNumber = 1000000;
20 char smallType = static_cast<char>(largeNumber); // Data loss!
21 std::cout << "After narrowing conversion: " << static_cast<int>(smallType) << std::endl;
22
23 return 0;
24}

Modern C++ Casting:

C++ provides several casting operators for different scenarios:

  • static_cast<type>(expression) - For "well-behaved" conversions
  • dynamic_cast<type>(expression) - For safe downcasting of polymorphic objects
  • const_cast<type>(expression) - To add or remove const qualifier
  • reinterpret_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.

C++
1#include <iostream>
2#include <string>
3
4int main() {
5 // Let the compiler deduce the types
6 auto intValue = 42; // int
7 auto doubleValue = 3.14; // double
8 auto charValue = 'A'; // char
9 auto text = "Hello, auto!"; // const char*
10 auto message = std::string("Hi"); // std::string
11
12 // Displaying the values
13 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;
18
19 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:

  1. Declares variables for a person's name, age, height (in meters), and whether they are a student
  2. Initializes these variables with appropriate values
  3. Displays all this information in a formatted way

Exercise 2: Type Conversion

Write a program that:

  1. Declares a floating-point variable with a value like 9.99
  2. Converts it to an integer (notice what happens to the decimal part)
  3. Converts the integer to a character and displays it
  4. 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

Introduction to C++

Learn the basics of C++ programming language.

Continue learning

Setting Up C++ Environment

Set up your development environment for C++ programming.

Continue learning

Control Flow in C++

Learn about decision making and loops in C++.

Continue learning

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.

C++
1#include <iostream>
2
3// C++ enums with strong typing (not available in C)
4enum class Color { Red, Green, Blue };
5enum class Status { Active, Inactive, Pending };
6
7int main() {
8 // C++ strongly typed enums
9 Color color = Color::Blue;
10 Status status = Status::Active;
11
12 // Cannot directly compare different enum classes (type safety)
13 // if (color == status) { } // Compilation error
14
15 // Type traits and type info (C++ feature)
16 std::cout << "Type of color: " << typeid(color).name() << std::endl;
17
18 return 0;
19}

2. Structs

Structs are user-defined types that group together related variables.

C++
1#include <iostream>
2#include <string>
3#include <memory> // For smart pointers
4
5// C++ struct with methods and access specifiers
6struct Person {
7private:
8 std::string name;
9 int age;
10
11public:
12 // Constructor
13 Person(std::string n, int a) : name(n), age(a) {}
14
15 // Methods within struct (not possible in C)
16 void display() const {
17 std::cout << "Name: " << name << ", Age: " << age << std::endl;
18 }
19
20 void birthday() {
21 age++;
22 std::cout << name << " is now " << age << " years old." << std::endl;
23 }
24};
25
26int 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();
31
32 return 0;
33}

3. Smart Pointers

Smart pointers are objects that manage the lifetime of dynamically allocated objects.

C++
1#include <iostream>
2#include <memory> // For smart pointers
3
4int main() {
5 // Modern C++ smart pointers (not in C)
6 std::unique_ptr<int> ptr = std::make_unique<int>(42);
7
8 // Displaying the value
9 std::cout << "Value: " << *ptr << std::endl;
10
11 return 0;
12}

4. Type Traits

Type traits are templates that provide compile-time information about types.

C++
1#include <iostream>
2
3int main() {
4 // Type traits example
5 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;
8
9 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.