二元操作符的返回值
来源:互联网 发布:js获取css属性值 编辑:程序博客网 时间:2024/06/05 17:06
今天同事遇到了个奇怪的问题,我帮忙看了一下,发现了比较神奇的事情,记录一下。
模拟一下代码基本上是这样:
int a = 10 ;unsigned int b = 2 ;if (b - a < 0){// do something}
然后我发现 b - a < 0这个判断返回的是false,也就是这个if语句不成立。
google了一下在stackoverflow里找到了答案,这是C的标准,当 int 和 unsigned int 操作时,int会被强制转换成unsigned int ,也就是说 b - a的结果也是一个unsigned int,它的值总是>= 0的,在XCode 5.1上这段代码直接就给出警告了("Comparison of unsigned expression < 0 is always false")
下面是stackoverflow的链接:
http://stackoverflow.com/questions/6770258/how-do-promotion-rules-work-when-the-signedness-on-either-side-of-a-binary-opera
引用accepted answer中的一段,讲述在C中二元操作符是如何处理两个不同类型变量的。
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
- If either operand is of type
long double
, the other shall be converted tolong double
. - Otherwise, if either operand is
double
, the other shall be converted todouble
. - Otherwise, if either operand is
float
, the other shall be converted tofloat
. - Otherwise, the integral promotions shall be performed on both operands.
- Then, if either operand is
unsigned long
the other shall be converted tounsigned long
. - Otherwise, if one operand is a
long int
and the otherunsigned int
, then if along int
can represent all the values of anunsigned int
, theunsigned int
shall be converted to along int
; otherwise both operands shall be converted tounsigned long int
. - Otherwise, if either operand is
long
, the other shall be converted tolong
. - Otherwise, if either operand is
unsigned
, the other shall be converted tounsigned
.
[Note: otherwise, the only remaining case is that both operands are int
]
后记:其实这些内容在深入理解计算机系统这本书里早有介绍,只能说自己的基础还是不够,惭愧了,总之还要多读书啊。
- 二元操作符的返回值
- 二元判断操作符 ? 的写法
- Java二元操作符instance的用法
- 二元操作符重载
- 二元操作符重载
- 二元操作符重载
- 二元操作符&& 与一元操作符++的求解秩序
- 如何写二元操作符重载的成员函数版
- shell中if条件的二元操作比较符
- instanceof是Java的一个二元操作符
- PHP在做二元赋值运算的时候, 返回值并不是左值,而是一个临时变量
- PHP在做二元赋值运算的时候, 返回值并不是左值,而是一个临时变量
- 赋值操作符的返回值
- C++之二元操作符重载
- 第三章 一元和二元操作符
- Lua语法分析(3)- 二元操作符
- 二元运算符<<的理解
- 解决:操作符重载, 二元运算符的参数之一必须是包含类型
- 螺旋方阵
- $(this)
- oracle-awr 操作
- MapReduce的自制Writable分组输出及组内排序
- 上拉刷新 下拉加载
- 二元操作符的返回值
- 初窥O2O模式——实体店体验+线上销售(大部分摘自百度百科)
- 黑马程序员笔记——Java面向对象之多态
- Python 在 Eclipse报错 Undefined variable from import: setdefaultencoding
- Python怎么读写json格式文件
- JSP_<jsp:forward>应用
- android 请求网络异步加载
- i++ 是否为原子操作 和 Java中的volatile关键字
- 数字三角形——递归、递推、记忆化搜索