为什么char的符号没有在C中定义? [英] why is char's sign-ness not defined in C?

查看:44
本文介绍了为什么char的符号没有在C中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 标准规定:

ISO/IEC 9899:1999, 6.2.5.15(第 49 页)

ISO/IEC 9899:1999, 6.2.5.15 (p. 49)

三种类型 char、signed char 和unsigned char 统称为字符类型.这实现应将 char 定义为具有相同的范围,表示,和行为作为有符号字符或无符号字符.

The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.

确实 gcc 根据目标平台定义.

And indeed gcc define that according to target platform.

我的问题是,为什么标准会这样做?除了可怕且难以发现的错误之外,我看不到任何来自模棱两可的类型定义的东西.

My question is, why does the standard do that? I can see nothing that can come out of ambiguous type definition, except of hideous and hard to spot bugs.

不仅如此,在 ANSI C(C99 之前)中,唯一的字节大小类型是 char,因此有时不可避免地使用 char 进行数学运算.所以说一个人永远不应该使用 char 进行数学运算"并不是那么正确.如果是这样,更明智的决定是包含三种类型char,ubyte,sbyte".

More than so, in ANSI C (before C99), the only byte-sized type is char, so using char for math is sometimes inevitable. So saying "one should never use char for math" is not so true. If that was the case, a saner decision was to include three types "char,ubyte,sbyte".

这是有原因的,还是只是一些奇怪的向后兼容问题,以便允许将糟糕(但常见)的编译器定义为标准兼容?

Is there a reason for that, or is it just some weird backwards-compatibility gotcha, in order to allow bad (but common) compilers to be defined as standard compatible?

推荐答案

具有未指定符号的Plain" char 允许编译器选择对目标架构更有效的表示:在某些架构上,零扩展一个字节int"大小的值需要更少的操作(因此使普通字符无符号"),而在其他指令集上,符号扩展更自然,普通字符被实现为有符号.

"Plain" char having unspecified signed-ness allows compilers to select whichever representation is more efficient for the target architecture: on some architectures, zero extending a one-byte value to the size of "int" requires less operations (thus making plain char 'unsigned'), while on others the instruction set makes sign-extending more natural, and plain char gets implemented as signed.

这篇关于为什么char的符号没有在C中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆