Chinaunix首页 | 论坛 | 博客
  • 博客访问: 335261
  • 博文数量: 79
  • 博客积分: 2466
  • 博客等级: 大尉
  • 技术积分: 880
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-07 16:47
文章分类

全部博文(79)

文章存档

2014年(3)

2012年(7)

2011年(14)

2010年(2)

2009年(2)

2008年(2)

2007年(18)

2006年(31)

分类: C/C++

2011-10-30 21:15:58

The language does not specify whether variables of type char are signed or unsigned quantities. When a char is converted to an int, can it ever produce a negative integer? The answer varies from machine to machine, reflecting differences in architecture.

The definition of C guarantees that any character in the machine's standard printing character set will never be negative, so these characters will always be positive quantities in expressions. But arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others. For portability, specify signed or unsigned if non-character data is to be stored in char variables.  

The problem is that comparisons between signed and unsigned values are machine-dependent, because they depend on the sizes of the various integer types. For example, suppose that int is 16 bits and long is 32 bits. Then -1L < 1U, because 1U, which is an unsigned int, is promoted to a signed long. But -1L > 1UL because -1L is promoted to unsigned long and thus appears to be a large positive number.
所以比较无符号数和带符号数的时候,要特别小心。

If x is float and i is int, then x = i and i = x both cause conversions; float to int causes truncation of any  fractional part. When a double is converted to float, whether the value is rounded or truncated is implementation dependent.  

Right shifting an  unsigned quantity always fits the vacated bits with zero. Right shifting a signed quantity will fill with bit signs (``arithmetic shift'') on some machines and with 0-bits (``logical shift'') on others.
Java的解决方案是提供了两个右移操作符:
>>      Signed right shift
>>>     Unsigned right shift

“制作”一个最右边n个bit为1的mask:~(~0 << n)

C, like most languages, does not specify the order in which the operands of an operator are evaluated. (The exceptions are &&, ||, ?:, and `,'.) For example, in a statement like  
    x = f() + g();
f may be evaluated before g or vice versa; thus if either f or g alters a variable on which the other depends, x can depend on the order of evaluation. Intermediate results can be stored in temporary variables to ensure a particular sequence.  
Similarly, the order in which function arguments are evaluated is not specified.
The moral is that writing code that depends on order of evaluation is a bad programming practice in any language.

A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand. The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.
阅读(634) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~