gpt4 book ai didi

c - 为什么这个 sizeof(c+a) 给出 4 个字节而不是 3 个字节

转载 作者:行者123 更新时间:2023-12-03 19:50:09 26 4
gpt4 key购买 nike

#include <stdio.h>
int main()
{
short int a;
char c;
printf("%d %d %d",sizeof(a),sizeof(c),sizeof(c+a));
}

在这个 sizeof 中,a 是 2 个字节,char 的大小是 1 个字节,但我将它们加起来是 4 个字节。它在表达式内部做了什么使它成为 4

最佳答案

short int 添加到 char 会产生 int,这在您的系统上显然是 4 个字节。

这是“整数提升”的情况。参见 In a C expression where unsigned int and signed int are present, which type will be promoted to what type?寻求解释。规则相当困惑,但那里的答案解释得很好。

根据 the C standard6.3.1.8 普通算术转换 ,实际的转换规则是:

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned
integer type corresponding to the type of the operand with signed integer type.

结果是 4,因为正如@WeatherVane 在评论中指出的那样:

5.1.2.3 para 11 示例 2 在执行片段中 char c1, c2;/* ... */c1 = c1 + c2; “整数提升”要求抽象机将每个变量的值提升为 int 大小,然后将两个 int 相加并截断总和。 但这里没有截断,因为目的地未知。

关于c - 为什么这个 sizeof(c+a) 给出 4 个字节而不是 3 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46715691/

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