PDFVersion
No ads? No problem! Download the PDF book of this tutorial for just $24.99. Your support will help us reach more readers.
Thank You!
Sizeof() Operator:
The sizeof()
operator is a useful tool in C++ for determining the size, in bytes, of a given data type or variable. It helps in situations where the size of built-in types may vary across different computing environments. Let's delve into how it works:
sizeof(data-type); // Size of Data type
sizeof variable-name; // Size of Any Variable
The first form returns the size of the specified data type, while the second form returns the size of a specified variable.
If you want to determine the size of a data type, such as int
or char
you must enclose the type name in parentheses ()
. For variable size, no parentheses are needed, although you can use them.
To see the sizeof()
operator in action, consider the following program:
#include<iostream>
using namespace std;
int main() {
cout << "Integer data type" << endl;
cout << "size of int is " << sizeof(int) << endl;
cout << "size of signed int is " << sizeof(signed int) << endl;
cout << "size of unsigned int is " << sizeof(unsigned int) << endl;
cout << "size of short is " << sizeof(short) << endl;
cout << "size of signed short is " << sizeof(signed short) << endl;
cout << "size of unsigned short is " << sizeof(unsigned short) << endl;
cout << "size of long is " << sizeof(long) << endl;
cout << "size of signed long is " << sizeof(signed long) << endl;
cout << "size of unsigned long is " << sizeof(unsigned long) << endl;
cout << "\n\nCharacter data type" << endl;
cout << "size of char is " << sizeof(char) << endl;
cout << "size of signed char is " << sizeof(signed char) << endl;
cout << "size of unsigned char is " << sizeof(unsigned char) << endl;
cout << "size of wchar_t is " << sizeof(wchar_t) << endl;
cout << "\n\nFloating point data type:" << endl;
cout << "size of float is " << sizeof(float) << endl;
cout << "size of double is " << sizeof(double) << endl;
cout << "size of long double is " << sizeof(long double) << endl;
return 0;
}
The sizeof()
operator can be applied to any data type, including arrays, where it returns the number of bytes used by the array. It's important to note that sizeof is a compile-time operator. All information needed to compute the size of a variable or data type is known during compilation. This feature aids in generating portable code that relies on the size of C++ data types.
Remember, since the size of types in C++ is implementation-defined, it's not advisable to make assumptions about their sizes in code you write.
Sardar Omar
I did my hardest to present you with all of the information you need on this subject in a simple and understandable manner. However, if you have any difficulties understanding this concept or have any questions, please do not hesitate to ask. I'll try my best to meet your requirements.