T
Trishia Rose
this is something ive always wondered, does it take cpu time at run
time to typecast or just at compile time? for example consider the
two little bits of code:
int a = 5;
int b = a;
and:
char *a = (char*) 5;
int b = (int) a;
They both set b to the same thing (5), but does the 2nd one take more
cpu time at runtime?
I find that trick actually very useful in situations where you have a
rather long and often-edited (so that you dont want to copy and paste
a copy) utility function which is called in alot of places, one of
whose arguments is, say, an int, which is not necessarily used
(depending on another of its arguments, say, "int type"), and then
suddenly you realize it would be very useful to be able to pass a char
* to that utility function for some purpose while at the same time for
that same purpose you dont need to pass the int.
so for instance
void utility( int type, int argument )
{
switch( type )
{
case TYPE_HOUR:
printf( "The hour is currently %d.\n", argument ); break;
case TYPE_COUNT:
printf( "The count variable is currently %d.\n", argument ); break;
case TYPE_NAME:
printf( "The name variable is set to %s.\n", (char*) argument );
break;
}
}
Then you could do
utility( TYPE_HOUR, current_hour ); /* current_hour is an int */
utility( TYPE_COUNT, count ); /* count is an int */
utility( TYPE_NAME, (int) name ); /* name is a char pointer */
but the question is would this suck up tons of CPU time
unnecessarily...
time to typecast or just at compile time? for example consider the
two little bits of code:
int a = 5;
int b = a;
and:
char *a = (char*) 5;
int b = (int) a;
They both set b to the same thing (5), but does the 2nd one take more
cpu time at runtime?
I find that trick actually very useful in situations where you have a
rather long and often-edited (so that you dont want to copy and paste
a copy) utility function which is called in alot of places, one of
whose arguments is, say, an int, which is not necessarily used
(depending on another of its arguments, say, "int type"), and then
suddenly you realize it would be very useful to be able to pass a char
* to that utility function for some purpose while at the same time for
that same purpose you dont need to pass the int.
so for instance
void utility( int type, int argument )
{
switch( type )
{
case TYPE_HOUR:
printf( "The hour is currently %d.\n", argument ); break;
case TYPE_COUNT:
printf( "The count variable is currently %d.\n", argument ); break;
case TYPE_NAME:
printf( "The name variable is set to %s.\n", (char*) argument );
break;
}
}
Then you could do
utility( TYPE_HOUR, current_hour ); /* current_hour is an int */
utility( TYPE_COUNT, count ); /* count is an int */
utility( TYPE_NAME, (int) name ); /* name is a char pointer */
but the question is would this suck up tons of CPU time
unnecessarily...