为什么isdigit()如果为真则返回2048?

nou*_*fal 5 c c++ ctype

任何人都可以解释为什么如果真的isdigit返回2048?我是ctype.h图书馆的新手.

#include <stdio.h>
#include <ctype.h>
int main() {
  char c = '9';
  printf ("%d", isdigit(c));
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 22

因为它被允许.C99标准只说这一下isdigit,isalpha等:

当且仅当参数的值符合函数描述中的函数时,此子句中的函数才返回非零(true)c.

至于为什么在实践中发生这种情况,我不确定.在猜测中,它使用与所有is*函数共享的查找表,并屏蔽除特定位位置之外的所有位置.例如:

static const int table[256] = { ... };

// ... etc ...
int isalpha(char c) { return table[c] & 1024; }
int isdigit(char c) { return table[c] & 2048; }
// ... etc ...
Run Code Online (Sandbox Code Playgroud)

  • @Coodey:**`isdigit`的**实现不存在.有许多实现,其中没有一个是"最真实的". (4认同)
  • 我不知道这是否是`isdigit`的真正实现,但它似乎可以:http://www.jbox.dk/sanos/source/lib/ctype.c.html (2认同)