#include <stdio.h>
#define all_mem (sizeof(x) /sizeof(x[0]))
int x[] ={1,2,3,4,5,6,7,8,9,10};
int main(void) {
// printf("The condition is %d",(all_mem-2));
int i;
for(i=-1;i<=(all_mem-2);i++)
{
printf("The number is %d",i);
}
return 0;
}
在上面的循环代码中甚至没有执行一次,我尝试了打印条件并且它满足循环条件。任何见解如何将for循环条件中的宏表达式计算为小于-1的值?
答案 0 :(得分:2)
find / -iname abc.[]
宏返回all_mem
值;整数提升规则意味着size_t
正在推广i <= (all_mem - 2)
到i
的比较,这意味着价值很大,而不是size_t
。尝试投射以确保签名比较:
-1
答案 1 :(得分:0)
对代码进行一些更正后,forofance,sizeof()返回size_t
,而不是int
代码完美无缺。
以下是修改后的代码:
#include <stdio.h>
#define all_mem (sizeof(x) /sizeof(x[0]))
int x[] ={1,2,3,4,5,6,7,8,9,10};
int main(void)
{
printf( "all_mem = %ld\n", all_mem ); // << added for debugging
// printf("The condition is %d",(all_mem-2));
int i;
for(i=-1;i<=(int)(all_mem-2);i++) // <<
// << properly cast to int
// otherwise compiler raises warning and unsigned comparison made
{
printf("The number is %d\n",i);
}
return 0;
}
以下是上述代码的输出:
all_mem = 10
The number is -1
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
编译时,始终启用所有警告,然后修复这些警告。
如果遵循上述陈述,那么在没有我们帮助的情况下你会看到问题。
(对于gcc,至少使用:-Wall -Wextra -pedantic
并且我还添加:-Wconversion -std=c99
)