There is an unfortunate expression rule in C that may byte you here. It
states that anything smaller than int gets promoted to int in an expression.
The intent of the rule was that traditionally CPUs had only one size of data
that they operated on most efficiently--the width of the register. Making
that the "common denominator" would generate the most efficient code.
However when you use a processor like an x86 that can work with equal
efficiency on 8, 16 or 32 bit data, that little rule becomes a real
nuisance.
Often you won't notice the difference, but if you are doing things that
involve bit manipulation or bit masking and comparision, and you happen to
be using signed versions of things, the promotion will put a bunch of 1s in
the upper bits if the value had the MSB set, which is not anticipated.
Masking them out before testing works. It may generate extra code, or the
optimization may recognize the uselessness of the extra bits and optimize
them away.
A related issue is that the promotion to int takes at least one extra
instruction every time it occurs. Again, masking may clue the optimizer
into eliminating this, but at the expense of messy looking code.
Similar stuff happens when using char for numerical puposes. Again a
situation where at least on x86 the promotion rule is rather short sighted.
I can't think of a case where simply promoting to the largest size in the
expression wouldn't have generated equally correct code that often is more
compact and faster.
In fact I feel strongly enough about it that I think there should be a
compile switch that overrides the behavior. I'd leave it on all the time.
Again, I can't think of a single case where it would produce adverse
effects.
Wilton