【问题标题】:Why is (int64_t)-1 + (uint32_t)0 signed?为什么 (int64_t)-1 + (uint32_t)0 签名?
【发布时间】:2013-11-30 21:21:04
【问题描述】:

为什么(int64_t)-1 + (uint32_t)0 用 C 签名?看起来是int64_t,但我的直觉是uint64_t

仅供参考当我跑步时

#include <stdint.h>
#include <stdio.h>

#define BIT_SIZE(x) (sizeof(x) * 8)
#define IS_UNSIGNED(x) ((unsigned)(((x) * 0 - 1) >> (BIT_SIZE(x) - 1)) < 2)
#define DUMP(x) dump(#x, IS_UNSIGNED(x), BIT_SIZE(x))

static void dump(const char *x_str, int is_unsigned, int bit_size) {
  printf("%s is %sint%d_t\n", x_str, "u" + !is_unsigned, bit_size);
}

int main(int argc, char **argv) {
  (void)argc; (void)argv;
  DUMP(42);
  DUMP(42U);
  DUMP(42L);
  DUMP(42UL);
  DUMP(42LL);
  DUMP(42ULL);
  DUMP('x');
  DUMP((char)'x');
  DUMP(1 + 2U);
  DUMP(1 << 2U);
  DUMP((int32_t)-1 + (uint64_t)0);
  DUMP((int64_t)-1 + (uint32_t)0);
  return 0;
}

我得到以下输出:

42 is int32_t
42U is uint32_t
42L is int32_t
42UL is uint32_t
42LL is int64_t
42ULL is uint64_t
'x' is int32_t
(char)'x' is int8_t
1 + 2U is uint32_t
1 << 2U is int32_t
(int32_t)-1 + (uint64_t)0 is uint64_t
(int64_t)-1 + (uint32_t)0 is int64_t

【问题讨论】:

  • +1 为您的 IS_UNSIGNED(x) 宏。虽然我会使用 CHAR_BIT 而不是 8。

标签: c integer-promotion


【解决方案1】:

为什么 (int64_t)-1 + (uint32_t)0 有符号?

因为int64_t 转化排名大于uin32_t 转化排名。 (uint32_t)0+ 表达式中转换为int64_tint64_t 是结果表达式的类型。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 2013-07-25
  • 2012-06-13
  • 2016-08-31
  • 1970-01-01
相关资源
最近更新 更多