auto: let C++ choose the type
If the starting value already makes the type obvious, you can write auto and C++ picks the type for you:
#include <iostream>
using namespace std;
int main() {
auto count = 10; // C++ sees 10 and picks int
auto price = 4.5; // 4.5 has a decimal point, so double
auto letter = 'z'; // char
cout << count << " " << price << " " << letter << "\n";
return 0;
}Output
10 4.5 z
Tip:
autois handy later, when type names get long. While learning, writing the type yourself (int,double...) helps you understand your code better.
sizeof: how big is a type?
Every variable uses some memory, measured in bytes. sizeof tells you how many:
#include <iostream>
using namespace std;
int main() {
cout << "char: " << sizeof(char) << " byte\n";
cout << "bool: " << sizeof(bool) << " byte\n";
cout << "int: " << sizeof(int) << " bytes\n";
cout << "double: " << sizeof(double) << " bytes\n";
return 0;
}Output
char: 1 byte bool: 1 byte int: 4 bytes double: 8 bytes
An int uses 4 bytes. That is why it can only hold numbers up to about 2.1 billion. Go past that and the number overflows and wraps around to a negative number:
#include <iostream>
using namespace std;
int main() {
int biggest = 2147483647;
cout << biggest << "\n";
cout << biggest + 1 << "\n"; // too big for an int!
long long safe = 2147483647LL + 1;
cout << safe << "\n";
return 0;
}Output
2147483647 -2147483648 2147483648
Common mistake: Integer overflow is a real source of bugs – and even security holes! If your numbers can get big, use
long long.