谜语(C语言) [英] A riddle (in C)
问题描述
有一个朋友给了我一个谜语:
A friend gave me a riddle:
#include<stdio.h>
#define TOTAL_ELEMENTS ((sizeof(array) / sizeof(array[0])))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
getchar();
return 0;
}
以上code被认为能打印所有数组元素,什么是在code中的问题(输出什么)?我认为,循环不会遍历甚至一度?
The above code is supposed to print all the array elements, what is the problem in the code (the output is nothing)? I think the loop doesn't iterate even once?
我发现下面的code 确实工作
I found out that the following code does work:
#include<stdio.h>
#define TOTAL_ELEMENTS ((sizeof(array) / sizeof(array[0])))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
int x = (TOTAL_ELEMENTS-2);
for(d=-1;d <= x;d++)
printf("%d\n",array[d+1]);
getchar();
return 0;
}
我有一个理论,它的东西做的宏,但我不能把我的手指上的问题。
I have a theory that it's something to do with the macro, but I can't put my finger on the problem.
推荐答案
的问题是,(TOTAL_ELEMENTS-2)
是一个无符号值。当你作出比较 D&LT; =(TOTAL_ELEMENTS-2)
,这两个值被转换为无符号值,其结果是假的。
The problem is that (TOTAL_ELEMENTS-2)
is an unsigned value. When you make the comparison d <= (TOTAL_ELEMENTS-2)
, both values are converted to unsigned values, and the result is false.
在你的第二个例子, X
签订所以没有问题。
In your second example, x
is signed so there is no problem.
这篇关于谜语(C语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!