sergio masci wrote: >> It's also sometimes effective (code-wise) to give the compiler hints in >> the form of type casts about the expected size of intermediate results. > > oh... type casts, horrible nasty vicious things :-) > > Yes I understand what you're saying and I've done this many times myself, > but it's so incredibly dangerous. What you are essentially saying to the > compiler is "stop doing what you know is right and will work - do what I > tell you no mater how stupid it may be" (this is not intended to imply > that the programmer is in any way stupid :-) Not only this. Sometimes it is necessary, like a calculation on two ints with a result that will fit into an int, but the calculation itself needs to be performed as long; something like int aa=500, bb=1000, cc=700; // only example values, not const int result; // 1- the easy way, not good: result = (aa * bb) / cc; // 2- better (works): result = ((long)aa * bb) / cc; // 3- for longer calculations that involve multiple scaled // values my preference, often tracking the possible ranges // of input/output for some code lines in line comments: long temp = aa; temp *= bb; temp /= cc; ASSERT( (INT_MIN<=temp) && (temp<=INT_MAX) ); result = (int)temp; This is actually where we get back to James's original post. This manual tracking of ranges in comments as I sometimes do in such situations could somehow be formalized and at least be checked by the compiler, throwing warnings for calculations that may lead to data loss. > The problem with a type cast is that it prevents the compiler from coping > with changes you make to your code without telling you about it and > without extensive retesting you cannot be sure ANY changes you make will > have the effect you intended. That is correct. OTOH, whenever I change in resource-optimized code (where this is an issue) the type of a variable, I check every line of code where this variable is referenced. It's not only about rogue casts here; if you need to go from 1 byte to 2 bytes, it's usually because the possible range of values has increased. This may throw any numbers of other calculations off track, and you need to review every single of them to find out which other variables (and temp variables, and calculations with intermediate results) may need to be done with increased range. > you might be able to get around this potential problem by adding > > #if !(sizeof(A) == sizeof(B) && sizeof(A) == 1) > #error "unsafe hint detected" > #endif So in a sense, this is implied in all sources (or should be :). One should always treat it as "unsafe" when changing the range of a variable. Gerhard -- http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist