Calculating The Size of Any Data Type in C++ Using sizeof Operator

sizeof is a compile time operator that determines the size of a variable or data type in bytes.

You can use this operator to calculate size of any data type like intfloatchar and etc.

The syntax of using sizeof operator is as follows:


sizeof(data type);

Where data type includes constants, variables, classes, structures, unions or any other user defined data type.

sizeof cannot be used with function types or incomplete types etc.

 Recommended reading: C++ Program to Find Quotient and Remainder

C++ Source Code to Find Size of Any Data Type:

#include<iostream>
using namespace std;
int main()
{
	cout<<"Size of Character: "<<sizeof(char)<<" Byte"<<endl;
	cout<<"Size of Integer: "<<sizeof(int)<<" Bytes"<<endl;
	cout<<"Size of Float: "<<sizeof(float)<<" Bytes"<<endl;
	cout<<"Size of Double: "<<sizeof(double)<<" Bytes"<<endl;
	return 0;
}

Code Explanation:

First of all, we used cout statement to show appropriate messages on the screen.

After that we used sizeof operator to calculate the size of data types.

At first, we used data type “char”. At the end, we again used cout to print the sizes of data types on screen. Program told us that it takes 1 byte of memory which is true.

For another example, we placed “int” in the parenthesis and program showed that it takes 4 bytes memory.

You can also use this program to find size of other data types like long, short and etc.

 Recommended reading: Student Management System Project in C++

Output:

C++ Program To Find Size of Any Data Type

This was all about finding the size of any data type in C++ programming language.

If you liked this article, then I would really appreciate if you follow us on Twitter and Facebook.

If you have any question then you can ask me in comments. I would like to answer them.

You can also Click Here To Download Project Files.