short / char上的'〜'运算符隐式转换为int(C / gcc) [英] '~' operator on short/char implicitly casts to int (C / gcc)

查看:72
本文介绍了short / char上的'〜'运算符隐式转换为int(C / gcc)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用gcc的 -Wconversion 警告,看起来字符和短裤都隐式转换为整数。

With gcc's -Wconversion warning, It looks like chars and shorts are implicitly converted to ints.

#include<stdio.h>

#pragma GCC diagnostic warn "-Wconversion"

void main(void)
{
    short i = 1;
    short j = 1;
    short k = j & ~i;
    printf("value %d\n", j);
}

给出以下警告,

test.c: In function 'main':
test.c:9:15: warning: conversion to 'short int' from 'int' may alter its value [-Wconversion]
   short k = j & ~i;
               ^

重播短消息会使警告短k安静下来= j& (short)〜i; ,但这在变量类型已经匹配的情况下添加强制转换会有点奇怪。

Casting back to a short quiets the warning short k = j & (short)~i; but this is a bit strange adding casts where the variable types already match.

我调查了是否进一步,并且(无符号短)〜(无符号短)0 导致 0xffff

其中〜(unsigned short)0 导致 0xffffffff

I looked into if further and (unsigned short)~(unsigned short)0 results in 0xffff.
Where as ~(unsigned short)0 results in 0xffffffff

有人建议使用一种处理这些警告的好方法?

除了禁用 -Wconversion

Can anyone recommend a good way of dealing with these warnings?
Besides disabling -Wconversion.

推荐答案

根据C标准(6.5.3.3)整数提升的操作数上执行,结果为提升类型。整数促销(6.3.1.1)基本上表示所有小于 int 被提升为 int (如果 int 可以代表所有值原始类型)或 unsigned int (否则)。

According to the C standard (6.5.3.3), the integer promotions are performed on the operand of ~ and the result is of the promoted type. The integer promotions (6.3.1.1) basically say that all integer types smaller than int are promoted to int (if int can represent all values of the original type) or unsigned int (otherwise).

这篇关于short / char上的'〜'运算符隐式转换为int(C / gcc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆