gpt4 book ai didi

c - 递增一个字节并进行比较,是否定义了此行为?

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:22 24 4
gpt4 key购买 nike

假设 abcd 都声明为 unsigned char* 类型。以下代码片段中的行为是否定义明确?我担心的是当 cd[k] = 2551 添加到 cd[k],预期的行为是比较 ab[k] > cd[k] + 1 将等同于 b[k] > 256?不是 b[k] > 0?这是正确的吗?

if (ab[k] > cd[k] + 1)
{
r = 1;
}
else if (cd[k] > ab[k] + 1)
{
r = -1;
}

最佳答案

来自 C11 标准草案 N1570,§6.3.1.1.2:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.58) All other types are unchanged by the integer promotions.
[...]
58) The integer promotions are [...] as part of the usual arithmetic conversions, to certain argument expressions, to the operands of the unary +, -, and ~ operators, and to both operands of the shift operators, as specified by their respective subclauses.

简而言之,每个类型小于 intunsigned int 的表达式都被转换为 intunsigned int,分别。
int 必须至少 16 位宽,因此绝对不会发生回绕,您的表达式将产生 256

关于c - 递增一个字节并进行比较,是否定义了此行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245485/

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