ANSI C中类型转换

来源:互联网 发布:mac装双系统好吗 编辑:程序博客网 时间:2024/04/29 09:57

ANSI C中虽然对于类型转换定义的比较友好,但有时也会发生一些意想不到的错误,特别是在unsigned与signed之间的自动转换

如:

#include <iostream>using namespace std;int array[] = {23,34,12,17,204,99,16};#define TOTAL_ELEMENT (sizeof(array)/sizeof(array[0]))int main(){    cout<<TOTAL_ELEMENT;    int d = -1;    int x;    if(d < TOTAL_ELEMENT - 2){        cout<<"in"<<endl;        x = array[d+1];    }    system("pause");    return 0;}

其中由于sizeof函数返回的为unsigned int 类型,而根据ANSI C中的规范,在if中的比较语句中会将d进行转换,使其类型转为unsigned类型,进而使得该条件判断为false

附上ANSI C中类型转换规则:


0 0