Home C++ data types in C++ tutorial

data types in C++ tutorial

In C++, data types define the type of data a variable can hold, determining the amount of memory allocated and the operations allowed.

C++ provides a wide variety of data types, including primitive types, derived types, and user-defined types, allowing flexible and efficient management of data.

1. Basic Data Types

C++ provides several basic data types, including integer types, floating-point types, characters, and booleans.

Integer Types

Integers represent whole numbers. C++ offers several integer types with different sizes, including short, int, long, and long long.

#include <iostream>
using namespace std;

int main() {
    short s = 32767;          // 2 bytes
    int i = 2147483647;       // 4 bytes
    long l = 2147483647;      // 4 or 8 bytes (depending on system)
    long long ll = 9223372036854775807; // 8 bytes

    cout << "short: " << s << "\nint: " << i << "\nlong: " << l << "\nlong long: " << ll << endl;
    return 0;
}

Output:

short: 32767
int: 2147483647
long: 2147483647
long long: 9223372036854775807

Floating-Point Types

Floating-point types represent decimal numbers and include float, double, and long double for different levels of precision.

#include <iostream>
using namespace std;

int main() {
    float f = 3.14f;          // 4 bytes
    double d = 3.14159265359; // 8 bytes
    long double ld = 3.14159265358979323846L; // 10 or 16 bytes

    cout << "float: " << f << "\ndouble: " << d << "\nlong double: " << ld << endl;
    return 0;
}

Output:

float: 3.14
double: 3.14159265359
long double: 3.14159265358979323846

Character Type

The char data type is used to store individual characters, with a size of 1 byte. C++ also provides wchar_t for wide characters, char16_t, and char32_t for larger character encodings.

#include <iostream>
using namespace std;

int main() {
    char letter = 'A';
    wchar_t wideLetter = L'Ω';

    cout << "char: " << letter << "\nwchar_t: " << wideLetter << endl;
    return 0;
}

Output:

char: A
wchar_t: Ω

Boolean Type

The bool data type holds true or false values, used primarily for conditional expressions.

#include <iostream>
using namespace std;

int main() {
    bool isTrue = true;
    bool isFalse = false;

    cout << "isTrue: " << isTrue << "\nisFalse: " << isFalse << endl;
    return 0;
}

Output:

isTrue: 1
isFalse: 0

2. Modifiers with Data Types

Modifiers can change the characteristics of the basic data types, including signed, unsigned, short, and long.

#include <iostream>
using namespace std;

int main() {
    unsigned int uInt = 4294967295; // 4 bytes, no negative values
    signed int sInt = -2147483648;  // 4 bytes, supports negative values

    cout << "unsigned int: " << uInt << "\nsigned int: " << sInt << endl;
    return 0;
}

Output:

unsigned int: 4294967295
signed int: -2147483648

3. Derived Data Types

C++ provides several derived data types, including arrays, pointers, and references.

Array

An array is a collection of elements of the same type stored in contiguous memory locations.

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};

    for (int i = 0; i < 5; i++) {
        cout << "numbers[" << i << "] = " << numbers[i] << endl;
    }
    return 0;
}

Output:

numbers[0] = 1
numbers[1] = 2
numbers[2] = 2
numbers[3] = 4
numbers[4] = 5

Pointer

A pointer stores the memory address of another variable. It’s defined with the * symbol.

#include <iostream>
using namespace std;

int main() {
    int num = 10;
    int *ptr = # // Pointer to integer

    cout << "Address of num: " << ptr << "\nValue of num: " << *ptr << endl;
    return 0;
}

Output:

Address of num: 0x7ffeefbff568
Value of num: 10

Reference

A reference is an alias for another variable and is defined using the & symbol.

#include <iostream>
using namespace std;

int main() {
    int num = 100;
    int &ref = num; // Reference to num

    cout << "Original: " << num << "\nReference: " << ref << endl;
    ref = 200; // Modifies num through the reference
    cout << "Modified: " << num << endl;
    return 0;
}

Output:

Original: 100
Reference: 100
Modified: 200

4. User-Defined Data Types

C++ provides several user-defined types, including enum, struct, class, and union.

Enumeration (enum)

An enum is a user-defined type that consists of named integer constants, making code more readable.

#include <iostream>
using namespace std;

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday };

int main() {
    Day today = Wednesday;

    cout << "Today is: " << today << endl; // Outputs integer value of 'Wednesday'
    return 0;
}

Output:

Today is: 2

Structure (struct)

A struct is a user-defined type that groups multiple variables of different data types under a single name.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
};

int main() {
    Person person = {"Alice", 30};

    cout << "Name: " << person.name << "\nAge: " << person.age << endl;
    return 0;
}

Output:

Name: Alice
Age: 30

Class (class)

A class is similar to a struct but also includes member functions, making it a foundation of object-oriented programming in C++.

#include <iostream>
using namespace std;

class Rectangle {
    public:
        int width;
        int height;
        
        int area() {
            return width * height;
        }
};

int main() {
    Rectangle rect;
    rect.width = 10;
    rect.height = 5;

    cout << "Area: " << rect.area() << endl;
    return 0;
}

Output:

Area: 50

Union

A union is a user-defined data type where all members share the same memory location, making it efficient for memory management.

#include <iostream>
using namespace std;

union Data {
    int intValue;
    float floatValue;
};

int main() {
    Data data;
    data.intValue = 5;
    cout << "intValue: " << data.intValue << endl;

    data.floatValue = 3.14f; // Overwrites intValue due to shared memory
    cout << "floatValue: " << data.floatValue << endl;
    return 0;
}

Output:

intValue: 5
floatValue: 3.14

5. auto Type Deduction

The auto keyword in C++ allows the compiler to deduce the type of a variable at compile time.

#include <iostream>
using namespace std;

int main() {
    auto x = 10;       // int
    auto y = 3.14;     // double
    auto z = "Hello";  // const char*

    cout << "x: " << x << "\ny: " << y << "\nz: " << z << endl;
    return 0;
}

Output:

x: 10
y: 3.14
z: Hello

6. decltype Type Inference

The decltype keyword deduces the type of an expression without actually evaluating it, which can be useful for declaring variables of the same type as others.

#include <iostream>
using namespace std;

int main() {
    int num = 100;
    decltype(num) anotherNum = 200; // same type as num (int)

    cout << "num:

 " << num << "\nanotherNum: " << anotherNum << endl;
    return 0;
}

Output:

num: 100
anotherNum: 200

7. Summary Table of C++ Data Types

Data Type Example Description
Integer types int, short, long Stores whole numbers
Floating types float, double Stores decimal numbers
Character types char, wchar_t Stores single characters
Boolean bool Stores true or false
Modifier types unsigned, signed Modifies range of integer types
Array int arr[5] Collection of elements of the same type
Pointer int *ptr = &num Stores address of another variable
Reference int &ref = num Alias for another variable
Enum enum Day { Mon, Tue } Collection of named integer constants
Struct struct Person { } Groups variables of different types
Class class Rectangle { } Groups variables and methods for OOP
Union union Data { } Allows variables to share memory location
auto auto var = 10; Compiler deduces type at compile time
decltype decltype(num) x = 0; Deduces type of an expression

Complete Example: Using Different Data Types in C++

This example demonstrates the usage of various data types in C++.

#include <iostream>
using namespace std;

struct Car {
    string make;
    int year;
};

int main() {
    // Basic data types
    int age = 25;
    float height = 5.9;
    char initial = 'J';
    bool isStudent = false;

    // Array and pointer
    int scores[] = {90, 85, 80};
    int *ptr = scores;

    // User-defined type
    Car car = {"Toyota", 2015};

    // Printing all data types
    cout << "Age: " << age << "\nHeight: " << height << "\nInitial: " << initial << "\nIs Student: " << isStudent << endl;
    cout << "Scores: ";
    for (int i = 0; i < 3; i++) {
        cout << *(ptr + i) << " ";
    }
    cout << "\nCar make: " << car.make << "\nCar year: " << car.year << endl;

    return 0;
}

Output:

Age: 25
Height: 5.9
Initial: J
Is Student: 0
Scores: 90 85 80
Car make: Toyota
Car year: 2015

This tutorial demonstrates various data types in C++, providing a foundation for understanding how to work with different types of data in the language.

You may also like