Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What numeric type to choose for small loop counters? [closed]

Tags:

People also ask

What is the most appropriate data type for a loop counter?

In short, int is the default type you normally want to use when you don't have a fairly good reason to use something else.

Should we use Size_t or INT?

The signed equivalent of size_t is ptrdiff_t , not int . But using int is still much better in most cases than size_t. ptrdiff_t is long on 32 and 64 bit systems. This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful.

Which loop should be used if you know the number of iterations it needs to execute?

The while loop is used to perform an indefinite number of iterations, as long as a certain condition remains true. Pros: If the number of iterations is not known up front, then this is a case where a for loop can't be used. The while loop is quite simple.

What is the counter in a loop?

The loop counter is used to decide when the loop should terminate and for the program flow to continue to the next instruction after the loop.


Consider that int take 4 bytes in memory.

to understand what I'm looking for take this example :

for(x=0;x<10;x++) //do something

in this for instruction I know that the value of x is less than 11,

I have seen lot of code and most people declare x like an int,

why we shouldn't or why most people doesn't declare x like a short or even like a char !!

I thought in the reason and I found this explanation, for example :

short s=5;

s take 2 bytes in memory, and what I know is that the compiler consider 5 like an int so to put 5 to s, 5 should be converted to short right !!

-> so this instruction take less memory but more work

int i=5;

here i take 4 bytes but with no need for conversation (5 is an int)

-> so this instruction do less work but take more memory

is the reason something like what I thought !!

I hope that my question was clear