asuerhao's Blog

如果有什么做的不到的地方请尽管留言, 我会改进的 : )

C 数据类型转换

asuerhao posted @ 2012年4月28日 11:02 in 积累 with tags gcc c 数据类型 Turbo C , 1673 阅读

    看一下段代码, 分析for循环的循环体会执行多少次:

#include<stdio.h>
int main(void)
{
	int i;
	for(i=-1; i < sizeof(int); i++) {
		printf("%d, ", i);
	}
	return 0;
}

    实验表明, 在不同的编译器下, 这个循环的实现也不一样:

    1. 在gcc下, 由于'sizeof(int)'的返回值是'unsigned long int'类型的, 但'i'的类型是'signed int'类型的, 二者在做比较时要将i从'signed int'转换成'unsigned long int', 但由于i原来是有符号的'-1', 转换后变为无符号的'0xffffffff', 当然比'sizeof(int)'大, 结果for循环体一次也没有执行.

    2. 在Turbo C下, 由于'sizeof(int)'的返回值是'signed int'类型的(注意: 这不符合C标准的规定), 所以与'i'比较是没有类型转换, for循环体会执行5次.

    严重注意: 有些东西了解就行, 以便在出现问题时知道如何解决, 但尽量不要在自己的代码中尝试那些东西.

Avatar_small
Parivahan Sarathi 说:
2022年8月02日 16:22

Parivahan portal developed by Ministry of Roads Transport and Highways, Government of India. In India, RTO Act been followed strictly to tackle the issue of accidents and other road issues. The Government of India has brought the Parivahan online website, Parivahan portal developed by Ministry of Roads Transport and Highways, Government of India. Parivahan Sarathi In India, RTO Act been followed strictly to tackle the issue of accidents and other road issues.to bring the details of all vehicles and their owners to this website. Having information about vehicles on one website helps a lot during the investigation of accidents in India.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter