gpt4 book ai didi

忽略符号的 C 编译器标志

转载 作者:行者123 更新时间:2023-12-04 10:13:44 26 4
gpt4 key购买 nike

我目前正在处理从第三方承包商处购买的代码。一个结构有一个 unsigned char 字段,而他们将该字段传递给的函数需要一个 signed char。编译器不喜欢这样,因为它认为它们是不匹配的类型。但是,它显然是为该承包商编译的。一些谷歌搜索告诉我“[i]t 是实现定义的 char 对象是否可以包含负值”。承包商的编译器是否可以基本上忽略有符号/无符号类型并将它们视为相同?或者是否有一个编译器标志将它们视为相同?

C 不是我最擅长的语言——只要看看我在用户页面上的标签——所以任何帮助都将不胜感激。

最佳答案

其实charsigned charunsigned char是三种不同的类型。来自标准 (ISO/IEC 9899:1990):

6.1.2.5 Types

...

The three types char, signed char and unsigned char are collectively called the character types.

(例如在 C++ 中,如果你有一个 char 参数,你必须(或至少应该)用它们的三个变体编写覆盖函数)

普通 char 可能被编译器处理为有符号或无符号,但标准说(也在 6.1.2.5 中):

An object declared as type char is large enough to store any member of the basic execution character set. If a member of the required source character set in 5.2.1 is stored in a char object, its value is guarantied to be positive. If other quantities are stored in a char object, the behavior is implementation-defined: the values are treated as either signed or nonnegative integers.

An object declared as type signed char occupies the same amount of storage as a ''plain'' char object.

5.2.1所指字符为A-Z、a-z、0-9、空格、制表符、换行符及以下29个图形字符:

! " # % & ' ( ) * + , - . / :
; < = > ? [ \ ] ^ _ { | } ~

回答

我解释的所有这些基本上意味着值小于 128 的 ascii 字符保证为正。因此,如果存储的值始终小于 128,那应该是安全的(从保值的角度来看),尽管这不是很好的做法。

关于忽略符号的 C 编译器标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1362369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com