dspfun said:
Hi,
Is it recommended to use char instead of int for variables that you
know never will contain a value larger than 255? A small example
follows:
#include <stdio.h>
int main(void)
{
//int i = 1;
char i = 1; //is this better than previous line?
printf("i=%d\n",i);
return 0;
}
What are the pros and cons of using char instead of int when values
will not exceed 255?
As a general rule it's better to use 'int' or 'unsigned int' (or
wider) than any narrower type such as 'short' or 'char' (or the
unsigned variants of those). There are two reasons for this
general rule. One, the behavior upon use in computation is often
unexpected and sometimes surprising. Two, usually the savings in
data and/or code size is either small, non-existent, or negative
(and ditto for speed). Also, it depends on what kind of variable
you're talking about -- it's almost always a bad idea to use a
type like 'short' or 'char' for a simple parameter or automatic
variable (here simple means scalar, ie, not arrays or members of
structs/unions).
Understanding that the general rule is right a lot more often
than it's wrong, here are some more-or-less standard
counterexamples --
arrays when the arrays are large
members of struct or union types, when
a) there will be lots of the outer struct/union type
b) the exact layout is constrained for some other reason
specific resource limitations or constraints, eg,
a) extremely limited global data space
b) extremely limited stack space
c) trading code space for data space or vice versa
d) trading speed for space or vice versa
using a narrow type can enforce a desired range limit, eg
a) an index to a 256 element array (and CHAR_BIT == 8)
b) similarly for arrays with 65,536 elements
c) want to do some computations modulo 256 or 65536
(which happens "for free" by storing into 'unsigned
char' or 'unsigned short' variables)
Notice that the kinds of considerations that go into the
different counterexamples are often quite different from
one to another.
Hopefully this outlines gives you a good sense of the
"shape" of the pros/cons you're looking for, and will
let you make better decisions when new cases come up.
Also, one other consideration, which is code evolution. In the
particular case you give above, it may be short sighted to use
'char' because "you know it will never contain a value larger
than 255". Perhaps that's true for the code as it is today, but
who knows how the code might change tomorrow? Unless there are
definite reasons for believing a particular value will _never_ be
exceeded, it's usually better to expect that it will.