c - 在编译时和运行时保证 ASCII 的最佳方法是什么?

标签 c language-lawyer

我的灵感来自this answer .

我想到的一种方法是结合使用static_assert(C11-onwards)和assert

基本上,一个带有一堆的 ascii.h 文件

static_assert(' ' == 32);
static_assert('!' == 33);
// ...

语句然后是函数

static void assert_runtime_ascii(void) {
    assert(' ' == 32);
    assert('!' == 33);
    // ...
}

main中执行。

这太冗长了(200 多行),因此不切实际,所以我只是评论一下

// NOTE: this program expects ASCII both at run-time and compile-time.

完成。

有更好的方法吗?

我在标准中找不到类似 __STDC_IEC_559__ 的 ASCII 的 #define

有更好的方法吗?

最佳答案

best way to guarantee ASCII both at compile-time and run-time?

听起来OP想知道如何检测执行字符集编码和用户I/O编码。

在编译时运行时,要检测 ASCII,请使用一系列 _Static_assertsasserts (example code)对于大多数 128 ASCII字符,属于 C 语言执行字符集的一部分。 C11 §5.2.1 3

A to Z
a to z
0 to 9
! " # % & ’ ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~
space character, 
  and control characters representing horizontal tab, vertical tab, and form feed.
some way of indicating the end of each line of text

请注意,像“$、@、`”这样的字符不属于执行字符集,因此“如果没有相应的成员,则会将其转换为实现定义的成员,而不是空(宽)字符”适用。

<小时/>

要检测用户输入/输出的编码,除了要求用户输入引用文本并对其进行代码检查之外,我没有找到其他解决方案。

关于c - 在编译时和运行时保证 ASCII 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60122693/

相关文章:

c - 为什么 sizeof 类型与整数比较返回 false

c - 退出函数的 noreturn 属性是否必要?

c++ - 哪个编译器(如果有的话)在参数包扩展中有错误?

c++ - sizeof(T) 增量中的字节智能指针算法 : Undefined Behaviour?

c - 如何在c中连接两个char数组?

C - 从 ‘void*’ 到 ‘void (*)()’ 的无效转换

c - 在 C 语言中使用 poll() 作为 TCP 服务器

c - "char board[N][N]"的类型是什么?

c++ - 具有虚拟析构函数的池分配器

c++ - 嵌套类名在封闭类模板中使用时是否被视为当前实例化