Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to type cast literals?

Tags:

c++

c

embedded

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;
like image 923
frank_010 Avatar asked Dec 23 '22 10:12

frank_010


1 Answers

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.

like image 110
John Bollinger Avatar answered Dec 26 '22 00:12

John Bollinger