Sizeof() operator
Maya is interested to learn programming languages. When she is learning, she had a doubt on how to find the size of the variable. In C++, we have the sizeof() operator, which is used to get the size occupied by a variable or value. Now, write a C++ program to declare a variable of character, integer, float, and double type and print their respective sizes.
OUTPUT FORMAT:
Print the corresponding size of a character, integer, float and double.
SAMPLE OUTPUT:
1
4
4
8
Answers
sizeof() in C++
The operator simply returns the size of whatever data type or variable is passed in it.
The 4 basic data types asked in the question, are:
double gives more precision than float. Also, the sizes and ranges can be different based on whether we add modifiers. Here, we consider the standard data types.
As asked, we just declare four variables and print their sizes.
Sizes.cpp
#include <iostream>
using namespace std;
int main() {
char c = 'F'; // Character
int i = 10; // Integer
float f = 3.142; // Float
double d = 3.141592653589; // Double
cout << "Size of char: " << sizeof(c) << " byte" << endl;
cout << "Size of int: " << sizeof(i) << " bytes" << endl;
cout << "Size of float: " << sizeof(f) << " bytes" << endl;
cout << "Size of double: " << sizeof(d) << " bytes" << endl;
return 0;
}