char c;
short int s;
int i;
unsigned int u;
long int l;
unsigned long int ul;
float f;
double d;
long double ld;
i = i+c; /* c is converted to int*/
i = i+s; /*s is converted to int*/
u = u+i; /*i is converted to unsigned int*/
l = l+u; /*u is converted to long int l*/
ul = ul+l; /*l is converted to unsigned long int ul*/
f = f+ul; /*ul is converted to float f*/
d = d+f; /*f is converted to double d*/
ld = ld+d; /*d is converted to long double ld*/
c语言会遵循另一条简单的转换规则,那就是把赋值运算右边的表达式转换成左边变量的类型。如:
char c;
int i;
float f;
double d;
i = c; /*c is converted to int*/
f = i; /*i is converted to float*/
d = f; /*f is converted to double*/
把浮点数赋值给整型变量会丢掉改数的小数部分:
int i;
i = 842.97; /*i is now 842*/
i = -842.97; /*i is now -842*/
如果某值在变量类型范围之外,那么将得到无意义的结果。
c = 10000; /*WRONG*/
i = 1.0e20; /*WRONG*/
f = 1.0e100; /*WRONG*/
如果浮点常量被赋值给float型变量时,一个很好的方法是在浮点常量尾部加上后缀f。如:
f = 3.14159f;
如果没有后缀,常量3.14159将是double类型,可能引起警告消息。
为了定义转换规则,C99允许每个整数类型具有“整数转换等级”。下面按从最高级到最低级的顺序排列。
(1)long long int , unsigned long long int
(2)long int , unsigned long int
(3)int , unsigned int
(4)short int , unsigned short int
(5)char , signed char , unsigned char
(6)_Bool
C99用整数提升取代了C89中的整值提升,可以将任何等级低于int和unsigned int 的类型转换为int(只要该类型的所有值都可以用int类型表示),或unsigned int。
网友评论