Re: Does Casting Slow a Program Down?



"PeterOut" <MajorSetback@xxxxxxxxxx> wrote in message
news:1170255047.573548.183190@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
If I had code like this.

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

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

would it run slower than this?

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

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

It usually depends on the compiler. Compilers vary greatly in the quality
of the optimizations they can perform.

However, in this particular case, the answer would usually be "NO". I have
not seen a compiler so poor that it would treat the two cases you gave
differently.

I would expect more variability in a case like this:

int x,y;
x = 10;
y = (char)x;

A clever compiler will recognize that with x==10, the cast has no effect. A
less clever compiler would actually truncate to a character than convert
back to an int.

In your example, most compilers will realize that the cast has no effect.
("Realize" is an inappropriate anthropomorphization of the compiler -- more
precisely, the expression trees it builds and the algorithms it applies ot
the trees will weed this out.)
--
David T. Ashley (dta@xxxxxxxx)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)


.



Relevant Pages

  • Re: about the array
    ... 3- If you cast to the wrong type by accident, ... are malloc and free. ... the compiler should issue a diagnostic - gcc ... unknown set of arguments, and return an int. ...
    (comp.lang.c)
  • Re: about the array
    ... I guess the bottom line is - if the cast isn't necessary, why do it, esp. ... the compiler should issue a diagnostic - gcc gives: ... it], and screw up, e.g., without the declaration, the compiler *should* ... maybe the int taken by the ...
    (comp.lang.c)
  • Re: It Pays to Enrich Your C Skills
    ... Check if you can score a perfect 10 (without using a compiler). ... int main{ ... struct bitfield { ... out if it is a negative integer constant or a constant expression ...
    (comp.lang.c.moderated)
  • OT: Re: Perl Peeves
    ... I see the result of a test being used as an int. ... the compiler just assumed you knew what you were doing ... introduced to the language later, so void * was unheard of in most code. ... This didn't mean bool was special, declaring it just signaled to the ...
    (comp.lang.perl.misc)
  • Re: OT: Re: Perl Peeves
    ... when I see the result of a test being used as an int. ... compiler just assumed you knew what you were doing and would ... This didn't mean bool was special, declaring it just signaled to the ... What "normalization of bool results is built into the compiler"? ...
    (comp.lang.perl.misc)