Get Size of Data Types using C++

Get Size of Data Types using C++

In C++, variables and expressions have a specific data type. The size of each data type depends on the compiler and the system. When writing high-performance applications in C++, it is important to know the size of each data type. This tutorial shows how to get the size of data types using C++.

In C++, the sizeof operator can be used to get the size of any data type in bytes. The following example prints to the console the size of each data type in bytes.

#include <iostream>

int main()
{
    std::cout << "Data type\tSize (bytes)" << std::endl;
    std::cout << "bool \t\t" << sizeof(bool) << std::endl;
    std::cout << "char \t\t" << sizeof(char) << std::endl;
    std::cout << "wchar_t  \t" << sizeof(wchar_t ) << std::endl;
    std::cout << "short \t\t" << sizeof(short) << std::endl;
    std::cout << "int \t\t" << sizeof(int) << std::endl;
    std::cout << "long \t\t" << sizeof(long) << std::endl;
    std::cout << "long long \t" << sizeof(long long) << std::endl;
    std::cout << "float \t\t" << sizeof(float) << std::endl;
    std::cout << "double \t\t" << sizeof(double) << std::endl;
    std::cout << "long double \t" << sizeof(long double) << std::endl;

    return 0;
}

Here is an example output on a typical 64-bit system:

Data type       Size (bytes)
bool            1
char            1
wchar_t         4
short           2
int             4
long            8
long long       8
float           4
double          8
long double     16

It is important to note that the size of each data type may vary depending on the system and the compiler used. For example, on some systems, the size of int may be 2 bytes, while on others it may be 4 bytes.

Leave a Comment

Cancel reply

Your email address will not be published.