I wanted to know when you all(experienced programmers) program in C++, how do you choose primitive data types? For instance, if you have a for loop that you know iterates 4 times, do you use unsigned short int or int8_t? Why? or why not? Is it all about optimizing memory?
There are so many types of int with different sizes, I figured there must be a reason.
I use the native word size when specialized sizes are not required. For example, I use unsigned int for all counting loops.
When accessing hardware, I use the specific size integers, such as uint16_t or uint8_t.
With modern desktop computers, which have a lot of memory and speed, there is no need for premature optimizations like worrying about variable sizes.
In embedded systems, especially where memory is constrained, variable sizes may make a difference.
The best practice is to get the program working correctly, then apply optimizations as required. A very small buggy program is not as useful as a large correctly and robust program. Same for speed.
Processors are really efficient when using their native word size. Word sizes vary depending on the processor. Some processors are 8-bit word sizes, some 16, others 32-bit (and yes, there are sizes between and greater).
Data that is not the size of the processor's word (register), may cause additional effort by the processor. For example, a processor that has a 16-bit word size would need to make two memory fetches to build a 32-bit quantity. A 32-bit processor will fetch 32 bits for a 16-bit quantity than may have to shift bits or mask bits to get the 16-bit quantity into the correct position in the processor's register.
Hardware registers come in different sizes. When there is a hardware register that is 8-bits wide, one doesn't want to write 32-bits to the register, which is why there is an 8-bit wide data type versus a 32-bit data type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With