So I am working on memory constrained embedded system and want to save as much bytes as possible. If, in my code if I have statements like:
b = a << 1;
or
b += 1;
where a
and b
are uint8_t
. Is it beneficial to type cast the literal to same type or is it done by compiler:
b = a << (uint8_t) 1;
b += (uint8_t) 1;
is it beneficial to tye cast the literal to same type or is it done by compiler:
You are at the mercy of the compiler with respect to how it stores the values of constants in binaries it creates. There is no special reason to think that casts such as you propose will change the representation used, as they nominally express runtime conversions (from int
, in this case). Moreover, and without going into details, C specifies that the operands of arithmetic operations will be promoted to a type at least as wide as int
for the purpose of computing the results of arithmetic operations. A compiler might plausibly pre-compute such a conversion, effectively nullifying your casts altogether.
Your casts might actually be worse, however, if they happen to prevent the compiler from recognizing opportunities to avoid storing constant values at all. For example, speculatively, if your target CPU has a specific instruction to increment the value of a register by exactly 1, then it might use that to implement
b += 1;
... but fail to recognize that it can do the same thing with
b += (uint8_t) 1;
... on account of (uint8_t) 1
being a non-primary expression.
Use casts sparingly, and only as necessary to describe the semantics of your program. Rely on your compiler to do a good job, and if it doesn't then look for a better one. Compilers for embedded environments can usually be relied upon to understand the importance of minimizing code size, and even compilers for general-purpose platforms often have options to request optimization for minimum code size.
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