Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an integer always used as the controlling variable in a for loop?

There are often times when you know for a fact that your loop will never run more than x number of times where x can be represented by byte or a short, basically a datatype smaller than int.

Why do we use int which takes up 32 bits (with most languages) when something like a byte would suffice which is only 8 bits.

I know we have 32 bit and 64 bit processes so we can easily fetch the value in a single trip but it still does consume more memory. Or what am I missing here?

UPDATE: Just to clarify. I am aware that speed wise there is no difference. I am asking about the impact on memory consumption.

like image 990
uriDium Avatar asked Nov 17 '10 13:11

uriDium


People also ask

Which variable is used in for loop?

A common identifier naming convention is for the loop counter to use the variable names i, j, and k (and so on if needed), where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers.

Why is i always used in for loops?

always try to initialize a variable with a proper meaningful name.it will help to debug the program easily. It is common practice to use i in for loops. This is just what programmers are used to. It may relate to the concept of dimension in 3D space in mathematics.

What is i and J in programming?

i=iteration while j=after interation.

What is loop variable?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure. A loop variable is a classical fixture in programming that helps computers to handle repeated instructions.


1 Answers

In C, an "int" is defined as the most efficient integer type for the current machine.

It usually match the registers of the CPU, that's how it is the most eficient.

Using a smaller type of integer value may result in some bit-shifting or bit masking at the CPU level so you would get no gain...

like image 154
siukurnin Avatar answered Sep 21 '22 11:09

siukurnin