许久没有遇到的问题
C语言真是博大精深,越使用它,就越发感觉到它的威力和恐怖,最近在做算法的时候,遇到了一个强转的错误,把人折腾的够受,这次要好好梳理一下了,希望下次不能再犯此类的问题。
强制转换
强转是一个code中常用的做法,但是稍不留神,就会陷入算法失灵的境地,面对几十万行的代码,找到其中一个性能的问题,这种是非常考验人的。弄不好的会把人折腾的“飘飘欲仙”--头脑发胀,两眼发黑的那种。
强转的一个例子
下面一个例子说明了强转中哪些写法是不对的:
#include <stdio.h> int main() { double testa = 0.34545,testb = 0.001,testf = 0.0; short testd = 1234; short *teste = malloc(10*sizeof(short)); double testc = testd; teste[1] = 4; // this code is right testa = testb - (double)teste[1]; // it's wrong way testf = testb - teste[1]; printf("one teste:%lf teste:%d \n\r",(double)teste[1],teste[1]); printf("two testf:%f \n\r",testf); printf("three teste:%f testa:%lf \n\r",testf,testa); free(teste); return 0; }
强转的注意事项
1.类型bai说明符和表达式都必须加括号。
如把(int)(x+y)写成dao(int)x+y则成了把x转换成int型之后再与y相加了。
2.无论是强制转换或是自动转换,都只是为了本次运算的需要而对变量的数据长度进行的临时性转换,而不改变数据说明时对该变量定义的类型。
3. 一定要检查强转之后的数据是否越界。