比较int与long和其他 [英] Comparing int with long and others

查看:128
本文介绍了比较int与long和其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有这样的事情:

I am wondering if things like this :

int a = ...;
long b = ...;

if (a < b)
     doSomethings();

始终有效(除了未签名)

always works (excepted for unsigned)

我刚刚测试了几个值,但我想确定。我假设 a 在比较中被强制转换为长期,其他类型呢?

I just tested with a few values, but I want to be sure. I assume a is cast to long in the comparison, what about others type ?

推荐答案

int / long 比较始终有效。 2个操作数转换为通用类型,在这种情况下 long ,所有 int 都可以转换为 long 没有问题。

int/long compare always works. The 2 operands are converted to a common type, in this case long and all int can be converted to long with no problems.

int ii = ...;
long ll = ...;
if (ii < ll)
   doSomethings();

unsigned / long 比较总是有效,如果 long 范围超过 unsigned 。如果 unsigned 范围是 [0 ... 65535] long [ - 2G ... 2G-1] ,然后操作数转换为 long 和所有 unsigned 可以转换为 long ,没有任何问题。

unsigned/long compare always works if long ranges exceeds unsigned. If unsigned range was [0...65535] and long was [-2G...2G-1], then the operands are converted to long and all unsigned can be converted to long with no problems.

unsigned uu16 = ...;
long ll32 = ...;
if (uu16 < ll32)
   doSomethings();

unsigned / long 比较有问题 long 范围不超过 unsigned 。如果 unsigned 范围是 [0 ... 4G-1] long [ - 2G ... 2G-1] ,然后操作数转换为 long ,随后不包含范围和问题的常见类型。

unsigned/long compare has trouble when long ranges does not exceed unsigned. If unsigned range was [0...4G-1] and long was [-2G...2G-1], then the operands are converted to long, a common type that does not encompass both ranges and problems ensue.

unsigned uu32 = ...;
long ll32 = ...;

// problems
if (uu32 < ll32)  
   doSomethings();

// corrected solution
if (uu32 <= LONG_MAX && uu32 < ll32)  
   doSomethings();

// wrong solution
if (ll32 < 0 || uu32 < ll32)  
   doSomethings();

如果输入 long long 包括所有范围 unsigned ,代码可以使用比较至少 long long width。

If type long long includes all the range of unsigned, code could use do the compare with at least long long width.

unsigned uu;
long ll;
#if LONG_MAX >= UINT_MAX
  if (uu < ll)  
#if LLONG_MAX >= UINT_MAX
  if (uu < ll*1LL)  
#else 
  if (uu32 <= LONG_MAX && uu32 < ll32)  
  // if (ll < 0 || uu < ll)  
#endif

这篇关于比较int与long和其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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