代码做了什么?

时间:2016-05-26 07:04:25

标签: c

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

上面的代码执行速度比c中的标准scanf()快     和cin在c ++?它是如何执行的?

1 个答案:

答案 0 :(得分:1)

此代码不是将输入转换为整数的正确尝试。

// converts input to integer, result will be in *a.
// there are a little chances that function with to while loops will be inlined.
// also "int fastRead()" would be at least not slower than void fastRead(int*) 
inline void fastRead(int *a)
{
register char c=0;
// characters with ascii codes from 0 to 31 is control characters
// 32 is space. So this line just skips anything what control or space 
while (c<33) c=getchar_unlocked();
*a=0; // assign 0 to result
while (c>33)
{
    // if read character is digit ('0'-'9') then c-'0' will return a number
    // from 0 to 9, if it not the result of calculation will be wrong
    *a=*a*10+c-'0'; 
    c=getchar_unlocked();
}
}

即使速度非常快,我也不会在生产中使用这些代码。因为每个人都可以创建快速但错误的程序:)

相关问题