c - 这个函数做了什么来帮助它以不同的方式接受输入以及 for 循环中的条件是如何执行的
问题描述
这个函数做了什么来帮助它以不同的方式接受输入,以及 for 循环中的条件是如何执行的?
void scanint(int &x)
{
int flag=0;
register int c = gc();
if(c == '-') flag=1;
x = 0;
for(;(c<48 || c>57);c = gc());//why is this used?
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}//how is this executed ?
if(flag == 1)x=-x;
}
解决方案
这不是c。
void scanint(int &x) {/* Whatever */}
// ^^
这定义了一个接受对 an的引用int
的函数,并且在 c 中没有引用,参数按值传递给函数。您当然可以使用指向 的指针,int
但是应该相应地更改函数的主体,*x
使用x
.
以下假设gc()
代表类似于 的函数getchar()
,因此发布的代码是从中提取值的一种非常糟糕的方式:int
stdin
void scanint(int &x) // Or 'int *x' in C
{
int c = gc(); // register was deprecated in C++17
bool is_negative = (c == '-'); // C has bool from C99 too
x = 0; // '*x = 0;' in C. The same applies to the following code
// Considering only ASCII, ignores non-digit characters
// E.g. from " 123" it ignores the first two spaces,
// but, given " -123", it will ignore the sign too. Bad, as I said.
for( ;
( c < '0' || c > '9');
c = gc() )
;
// Now computes the actual number using an old trick that should
// be left to the compiler to be exploited:
// 10 * x = (2 + 8) * x = 2 * x + 8 * x = x << 1 + x << 3 (bit shifts)
for( ;
'0' <= c && c <= '9';
c = gc() )
{
x = (x << 1) + (x << 3) + c - '0';
}
if ( is_negative )
x = -x;
}
推荐阅读
- xslt - XSL lookup from a properties (csv) file
- authentication - 使用 JWT 与 Asp.net 核心进行 GraphQL 身份验证
- mysql - 用数组值拆分逗号分隔的字符串
- xamarin.forms - Xamarin Forms - iOS - 返回按钮标题
- service-worker - 将 Google Workbox setDefaultHandler // setCatchHandler 从 v2 迁移到 v3
- javascript - 从反应中的输入字段获取值
- json - 使用 CURL 向训练数据添加查询
- mysql - 如何从 2 个重复行中只删除一行?
- javascript - 反应列表选择选项
- reactjs - 在 React 应用程序中导入 CSS