I've been reading the book "C++ Primer, Fifth Edition" and I stumbled upon something I seem to be unable to grasp:
A decimal literal has the smallest type of int, long, or long long
(i.e., the first type in this list) in which the literal’s value fits. Octal and hexadecimal
literals have the smallest type of int, unsigned int, long, unsigned long,
long long, or unsigned long long in which the literal’s value fits. It is an error
to use a literal that is too large to fit in the largest related type. There are no literals
of type short.
I suppose it is a simple concept, yet I cannot process it.
auto x = 3; //3 is a literal. Because auto is used the compile may choose the smallest from the list in the quote, which is type int (and int varies in size depending on your compiler/machine).
you can't have a literal larger than what will fit into the biggest for your compiler/system, which currently is 'usually' 64 bits or 8 bytes. It uses the same rules no matter what form you type the value.
And this is my problem with his writing. Its precise, but its overly done and like reading a lawyer's document. I don't recommend his books for beginners, though many do.
well, its nice to use the registers byte-wise for bytes and short-wise for shorts for machines that allow this. You can store 8 distinct values in the ?AX register of intel machines now. If you tell the machine those 8 values are ints, you can only store 1 of them unless the optimizer knows how to deal with that. I don't know how it handles that situation. You can force the issue, if you need this level of performance / space optimizations. It probably does not matter in most code, but registers are precious resources.
rax overlaps with a single 32-bit register, a single 16-bit register, and two 8-bit registers. There's no way to address all individual bytes of rax without shifting and masking. So you can't optimize register allocation by using smaller types.
More generally, I don't think there's any performance advantage in using smaller registers in x86/-64; I would need to see evidence of otherwise. Actually, I doubt any but the absolute cheapest microcontrollers will run faster when operating on smaller types.
Using smaller types may have an effect if you can fit more data in the cache, though, so make your arrays compact, when possible.