Does Casting Slow a Program Down?

I

Ian Collins

Peter said:
Nope. Virtually every high end server box I've used has had an
implementation where short and int are the same size. Note that
gcc is often configurable in that regard.
Care to name them?
 
K

Keith Thompson

CBFalconer said:
No it doesn't. Others have quoted the relevant portion in this
very thread.

I quoted the relevant portion myself, and I'm afraid your mistaken,
Chuck. Unsigned short promotes to unsigned int if (and only if)
signed int cannot represent the full range of unsigned short.

(Though I suppose there is a "shortage" of systems that do this, but
only because there's a shortage of systems where short and int are the
same size.)
 
B

Barry Schwarz

If I had code like this.

unsigned short usLimit=10
int a[10], i;

for (i=0; i<(int)usLimit; ++i)
{
a=(int)usLimit;
}

would it run slower than this?

int a[10], i, iLimit=10;

for (i=0; i<iLimit; ++i)
{
a=iLimit;
}


In your code, the conversion from unsigned short to int is required.
The conversion is performed as a result of the cast in the first
segment and as a result of promotion rules in the second segment.

To answer the question in your subject:

A *necessary* cast does not, by definition, slow down a program.
If you remove the cast, the program will not work properly. (If it
did, the cast would not be necessary.)

A *superfluous* cast, as in your example, should not slow down a
program. The conversion will be performed with or without the cast.
(If the conversion were performed only with the cast, it would not be
superfluous.)

An *poor* cast should slow down a program. Change the (int) to
(double) twice in your example. In the for statement, usLimit must be
converted from unsigned short to double and i must be converted from
int to double. In the assignment statement, usLimit must be converted
again (you indicated else-thread to not assume constant values) and
then converted from double to int. Even if the conversions to double
do not take longer than the conversions to int, the extra conversions
(i and double to int) should require more processing.


Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,254
Latest member
Top Crypto TwitterChannel

Latest Threads

Top