Size of int, float, double, char in C++
Print sizeof char, int, float, double, and long in C++. long is 4 or 8 bytes depending on the OS.
1#include <iostream>2using namespace std;34int main() {5 cout << "Size of char: " << sizeof(char) << " bytes" << endl;6 cout << "Size of int: " << sizeof(int) << " bytes" << endl;7 cout << "Size of float: " << sizeof(float) << " bytes" << endl;8 cout << "Size of double: " << sizeof(double) << " bytes" << endl;9 cout << "Size of long: " << sizeof(long) << " bytes" << endl;10 cout << "Size of long long: " << sizeof(long long) << " bytes" << endl;1112 return 0;13}
Output
Size of char: 1 bytes Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of long: 8 bytes Size of long long: 8 bytes
What's going on
This C++ program prints how many bytes char, int, float, double, long, and long long use, via sizeof. No input. Run it on your compiler — the numbers are the point.
sizeof(x) is bytes, and it's a compile-time value. You can write sizeof(int) or sizeof x on a variable. Same answer.
sizeof(char) is 1. Always. That's in the standard. The sample prints Size of char: 1 bytes (yes, "1 bytes" is grammatically wrong; the program doesn't pluralize).
sizeof(int) is 4 on almost every machine used for this course. Not a guarantee. Old textbooks still show 16-bit int.
sizeof(float) is usually 4, sizeof(double) 8. IEEE-754 on desktop compilers.
sizeof(long) is the annoying one: 4 on typical Windows, 8 on typical 64-bit Linux/macOS. The sample here shows 8. Print it. Don't copy a number from a website.
sizeof(long long) is 8 on every compiler you're likely to use. That's the type for values past 2 billion.
If long is 4 bytes, 1L << 40 will not do what a 64-bit long would. Use long long (or 1LL) when you mean 64 bits.