c - 为什么 `uint8_t`赋值给 `uint8_t`会出现转换警告?

标签 c type-conversion

为什么这段C代码:

#include <stdint.h>

uint8_t do_foo() {
  uint8_t int8;
  int8 = 0x80;
  int8 = int8 + (uint8_t) 1;
  return int8;
}

给这个编译器警告?

$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
$ gcc -c -Wall -Wextra -Wconversion test.c
test.c: In function ‘do_foo’:
test.c:6:10: warning: conversion to ‘uint8_t’ from ‘int’ may alter its value [-Wconversion]
   int8 = int8 + (uint8_t) 1;
          ^

据我所知,右边的表达式绝对是 uint8_t 类型,而不是 int 类型。

最佳答案

这是由于整数提升。

+的操作数小于int。因此,将它们提升为int,并在int中进行加法。

对于 int8 的赋值,结果必须转换回 uint8_t 导致警告,因为该值可能不适合。

关于c - 为什么 `uint8_t`赋值给 `uint8_t`会出现转换警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574514/

相关文章:

c - postgres共享连接问题

c - 参数类型不兼容且未在此函数中初始化

javascript - 如何在javascript中将字符串转换为文件对象?

java - 如何将 Java 对象转换为 JSONObject?

python - 从Python到PHP的for循环转换问题

php - PHP JSON解码数组中的数组到字符串的转换错误

c - 为什么 scanf 扫描空值

c - 为什么可以这样在struct中声明一个数组,又该如何使用呢?

c - 如何在创建多维数组后立即为其分配多个值 - 在 C 中?

c++ - 在 C 中将 char 转换为 int