Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use integers as loop counter variables?

Tags:

c

loops

I remember reading somewhere that it is better to use integers as loop counter variables rather than char or short. If yes, why? Does it provide any optimization benefits?

like image 782
Jay Avatar asked Feb 11 '10 09:02

Jay


3 Answers

Generally, the compiler will make int to be a good size for putting into one of your CPU's general purpose registers. That generally leads to fast access.

Of course there's no guarantee of anything. The compiler is free to do a lot of things, including, I would guess, promote some of your code that uses char to some larger type. So the difference might not even matter.

Really, for the answer that's true for your compiler, you should look at the assembly it outputs.

like image 126
asveikau Avatar answered Jan 30 '23 06:01

asveikau


In 32-bit architecture operations with 4 bytes (int) variables are usually faster. This is mainly due to size of registers and memory alignment. In 64 bit architecture it int will (should) be automatically made 64-bit integer.

like image 29
Alexey Kalmykov Avatar answered Jan 30 '23 06:01

Alexey Kalmykov


Alexey* is right, it's usually faster to use a type that's the same width as the architecture (i.e. an int32 for a 32 bit system)

Also, if you use a char i.e.

for(char i=0;i<max;++i)

there's a slight chance that you (or a colleague) will come back to the code in a month's time and change max to something high, causing an overflow and an annoying bug ;)

Sam

*and everyone else who answered while I was writing this!

like image 43
deanWombourne Avatar answered Jan 30 '23 06:01

deanWombourne