Author: Bruce Moreland
Date: 12:22:29 09/20/99
Go up one level in this thread
On September 20, 1999 at 12:56:30, Nicolas Carrasco wrote: >Thanks, > >I canĀ“t understand why ints are better than chars? > >Can u explain me? The compiler can do whatever it wants with an int, and what it typically does is make it the most efficient word-size for the machine. On an Intel machine an int is 32 bits, and the processor is very good at dealing with 32-bit quantities. In normal C implementation a char is 8 bits, and it's 8 bits even if the processor is bad at dealing with 8-bit quantities. Chars are typically used to store ascii text, processors aren't necessarily optimized to do math on them. The Intel processor, since it is terribly old, is pretty good at dealing with chars, but it's still a bad habit to use them when you don't need to. The 21164 Alpha chip, for instance, is bad at dealing with chars. You should use arrays chars for strings of text. If you have a structure that is stored on disk, or if you have a memory structure that really has to be small, to the point where performance is secondary to storage, it is OK to use chars in the structure. When you use a char in a structure like this, and you need to take the thing out of the structure for some reason, like to do math on it using automatic variables, or to pass it as a parameter, make your automatic and parameter variables ints, and let the compiler cast it for you, once, right there, rather than propagating chars all over your code. Here is some bad code: typedef struct char MF; typedef struct structMS { MF mf; ... // other stuff. } MS; MF MutateMf(MF mf) { ... // Do something to "mf" return mf; } void SomeFunc(MS * pms) { MF mf; mf = 6 + pms->mf; pms->mf = MutateMf(mf); } In the above example, it would be desirable to either change the typedef to "typedef int MF", or simply delete the line altogether and do a global replace of "MF" to "int". The problem with the above example now is that there are automatic variables and parameters that are of the "char" type when they should be ints. If it is really really necessary to have the MF in the MS structure be a char, it would be preferable to say "char mf" in the structure, while also making one of the changes in the preceding paragraph. This would allow the compiler to cast the stupid chars as necessary, and to be unaffected by them at other times. What you want is to get the elements out of the structure and deal with them as objects of the processor's natural size. None of this is a massive huge deal but these are good habits to adopt, they will help you when you want to port to a processor that has a different integer size, they will reduce the chances that you'll encounter some awful alignment problem, and the compiler and processor will have an easier time. bruce
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.