how fastread function is faster than scanf function?

please tell me that how fastread function performs faster than scanf
here is the code for fastread

inline void fastread(int* a)
{
    register char c = 0;
    while (c < 33)
        c = getchar();
    *a = 0;
    while (c > 33)
    {
        *a = *a * 10 + c - '0';
        c = getchar();
    }
}

check out this SO discussion…see the second ans…hope it will help…:slight_smile:

from the discussion
i think that its because the calling and return mechanism of function scanf takes much more time than getchar because scanf reads most of primitive types
am i getting it right?
but when i used the above function without the register storage class the whole program was taking more time.
so can you please give me more precise explanation of this?

I think the function is faster because of 2 reasons:-

1)the function fastRead does not perform any checking to see if a valid input is entered which i think scanf does. it just assumes you are entering integer format.

  1. variables stored in register are not part of the program stack hence their access time to I/O will be faster.

but register memory is limited means the mechanism must be moving value stored in register from there to actual array position.
while i think in scanf the value is stored directly to array position
so fastread must take some time in moving value from register to array memory location .
am i thinking it right way?

All operations have to use CPU registers, no memory operation can directly bypass from I/O to memory.so both use registers. i guess the main difference is what i mentioned in my 1st point.

but as i mention in my comment in above answer that if i am removing register from the above function then it is taking more time than scanf so i think that the key point is the use of register here.
but how?

@nishant_25 You have misunderstood the register storage class.

When you add the register modifier, if there is a register free, then the variable is put in that register. Then, automatically, operations involving this variable gets faster, as memory accesses are slow.

But, if there are not enough registers, then the variable is kept in memory, and the variable behaves just like normal behaviour. The execution speed will also be normal, just like there was no register modifier.

So, adding the register modifier, will not guarantee speed. But, if we get a register, then we get speed!

I got your point but even after above explanation why is this function fast ?

//