Re: Passing variables
"goodTweetieBird" <goodTweetieBird@hotmail.com> ha scritto nel messaggio
news:608e2e6c-59b8-43b4-8539-a63fafb34766@26g2000hsk.googlegroups.com...
In the function sender below it needs to send i as an unsigned char.
This function can be called by two functions, one of which is shown
below. timerExpire generates an int, the other already has it as an
unsigned char. Should i be cast to unsigned char before being sent to
sender. I think it would be a waste of time because of stack promotion/
conversions.
sender() expects 'int', so you don't need to cast 'int i' (defined in
timerExpire function) to 'unsigned char'.
When you use a function, you should consider the function as black-box, and
rely on its interface.
If you want sender() to accept unsigned char's, declare that in its
prototype:
void sender( unsigned char x )
void sender(int i)
{
/*
... do some stuff
*/
// This foreign fn requires i as unsigned char
ForeignFn((unsigned char) i, /* other vars */);
}
Here I would put at least an assert (ASSERT macro, or whatever), to check,
at least in debug builds, that the cast is safe.
I mean: ForeignFn expects an 'unsigned char', i.e. the valid values are in
range 0-255.
So, I would check that 'i' is in that range:
<code>
// Check 'i' range before casting to 'unsigned char'
ASSERT( i >= 0 && i <= 255 );
// Cast
ForeignFn( (unsigned char) i, ... );
</code>
Giovanni