Type-casting literals

Imagine you are working on a memory constrained embedded application, and want to save as much size as possible on the binary. The program has following shift-left statement:

res = val << 1;

How about you type-cast the literal 1 to the smallest possible data-type that can hold it? For example:

res = val << (uint8_t) 1;

Do you think this explicit casting of 1 into uint8_t worthwhile? One would hope it should save on the binary size by reserving only 8-bits to represent 1.

It turn out, the answer is NO. This is not helpful. Following reasons:

  • Arithmetic operand promotion: C/C++ automatically promote during compile-time all the operands to at least an int. So, in the example above the binary will hold literal 1 with unsigned int data-type. You can read more in detail about operand type promotion here: https://www.geeksforgeeks.org/integer-promotions-in-c/
  • The type-cast is normally a run-time operation. In our example, a run-time conversion from unsigned int to uint8_t. Therefore, it doesn’t help with our stated goal of saving on binary size which will contain unsigned int as mentioned in previous bullet.

So in conclusion – it’s not recommended to explicitly type-cast literals to smaller datatypes if the goal is to optimize on binary size. Note, there could be other reasons why you still might want to do that (e.g. to maintain sign-agreement).