on the use of char

Allan Sandfeld Jensen kde at carewolf.com
Thu Jul 29 11:11:03 BST 2004


On Thursday 29 July 2004 10:39, Matthias Welwarsky wrote:
> On Thursday 29 July 2004 04:34, Thiago Macieira wrote:
> > George Staikos wrote:
> > >   So if your goal is to store a relatively small number and not waste
> > > space, can I recommend either using a bitfield int, or thinking again
> > > "is it really worth the possible bugs in order to save 3 bytes out
> > > of, ex., ~5MB"?
> >
> > Let me also point out that it would only make sense to use char (or
> > signed char or unsigned char) in a struct, and only when you're careful
> > about padding.
> >
> > Using 'char' on the stack or on heap won't help you because variables
> > will be 4-byte aligned (or more) anyways. So you get 4 bytes allocated
> > despite the fact that you're using 'char'.
> >
> > If you write a struct like this:
> > 	struct {
> > 		char small;
> > 		int large;
> > 		int large2;
> > 	};
> >
> > then the struct is also 12 bytes in size and you're gaining NO space by
> > using char, at all.
>
> plus, on any architecture that has no means to access registers "char"-wise
> (i.e. most RISC), the compiler automatically adds code to mask the
> appropriate part of a register, if a char is involved in arithmetic
> operations. On ARM, something like
>
> 	for (char i=0; i < 1000; i++)
> 		bla;
>
> just does not make sense, except for burning cycles.
>
Except that it's an infinite loop, any decent compiler would register-allocate 
"i" here, which would mean very little penalty. Also all the modern RISC have 
byte-access by now, even alphas got it eventually.

> So not only you don't gain any memory space, you also add a performance
> penalty on many platforms. Of course this is mood since KDE mostly runs on
> ia32/ia64, but theres still PPC, Sparc, a.s.o...
>
> So char makes sense if you need to have bytewise access to something, or to
> represent large memory quantities, but it's inherently slow.
>
I agree. 

Also in cases where you worry about sizes (and you do if you use chars), I 
would lobby for using the C99-types: int8_t, uint8_t, int16_t and so forth. 
They are defined stdint.h on modern platforms and otherwise in inttypes.h. 
They are short and has weldefined signedness.

When size doesnt matter or speed specifically does, always use plain int.

`Allan




More information about the kde-core-devel mailing list