Help with casts

Garry Garrett garry at ceco.ceco.com
Fri Feb 22 12:46:45 AEST 1991


In article <1991Feb21.040145.8678 at cec1.wustl.edu>, abed at saturn.wustl.edu (Abed M. Hammoud) writes:
> 	I am new to C, and I have been a couple of times encountering
> 	the term lvalue...I looked it up in K&R C book but I still don't
> 	get it...
	
	I used to know.  (sorry, I forgot)

> 
> 	I also have another small question, please take a look at
> 	the two loops below and tell me if there is any difference
> 	in speed.
> 
> 		for (i=0; i < 100; i++)
> 		  x += i; 
> 
> 		As compared to...
> 
> 		for (i=0; i < 100; i++)
> 		  x += (float)i; 
> 

	Again, I don't know the answer to that either, but the reason that
I am responding is that I have some other hints for you to speed up you loop.
Consider:

		for (i=99; i; i--)
			x += i;

	I also recomend that you decare i as type "register int" or          
"register float".  This will save you alot of time if there is a free register
and you compiler can handle register variable.  
	Why is my for loop faster?  Your version must load i into a register,
load 100 into a register, compare them - putting the value of this comparision
into a register, and execute a BEQ (Branch if EQual) instruction.  My version
will load i into a register (if it isn't already in one), and execute a BZR
(Brand on ZeRo) instruction.  Almost no optimizing compiler will be able to
make this optimization for you.  In C, the value 0 is also logical false, and
any other value is true.  You can make your programs alot faster if you just
choose how to use 0 correctly.  In this case, counting "backwards" saves you
alot of time.  If we consider that each of the above instuctions takes a machine
cycle (I know, it may not work out that way) then your version takes twice as
long as mine, for each itteration.  Comming from fortran, this must all seem a
bit strange to you (counting backwards, using variables *as* conditions...) but
after you get used to it, it comes easy.  

Good luck.

Garry Garrett



More information about the Comp.lang.c mailing list