c – 对unsigned int进行一元操作的编译器警告

前端之家收集整理的这篇文章主要介绍了c – 对unsigned int进行一元操作的编译器警告前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个示例代码生成以下警告(带SP1的VS2008编译器):

warning C4146: unary minus operator
applied to unsigned type,result still
unsigned

码:

void f(int n)
{
}

int main()
{
    unsigned int n1 = 9;
    f(-n1);
}

但是因为函数f将它的参数作为int而不应该编译而没有任何警告?

解决方法

标准5.3.1 / 7

The operand of the unary – operator
shall have arithmetic or enumeration
type and the result is the negation of
its operand. Integral promotion is
performed on integral or enumeration
operands. The negative of an unsigned
quantity is computed by subtracting
its value from 2n,where n is the
number of bits in the promoted
operand. The type of the result is the
type of the promoted operand.

关于积分促进4.5 / 1的段落

An rvalue of type char,signed char,
unsigned char,short int,or unsigned
short int can be converted to an
rvalue of type int if int can
represent all the values of the source
type; otherwise,the source rvalue can
be converted to an rvalue of type
unsigned int.

即unsigned int不会被提升为int.

原文链接:https://www.f2er.com/c/117692.html

猜你在找的C&C++相关文章