C++ C++;for循环中的宏错误
我对以下代码有问题。 第一个for循环打印数组中的所有元素,而第二个for循环不打印任何东西。为什么?C++ C++;for循环中的宏错误,c++,c,C++,C,我对以下代码有问题。 第一个for循环打印数组中的所有元素,而第二个for循环不打印任何东西。为什么? #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main()
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
//Working
for(d=0;d < (TOTAL_ELEMENTS);d++)
{
cout << array[d] <<endl;
}
//This does not work. Why does this code fail? Isn't it same as the one above?
//If I assing TOTAL_ELEMENTS to a variable and then use that in for loop (below), it works! Why?
for(d=-1; d < (TOTAL_ELEMENTS);d++)
{
cout << array[d + 1] << endl;
}
}
#定义总元素(sizeof(数组)/sizeof(数组[0]))
int数组[]={23,34,12,17204,99,16};
int main()
{
int d;
//工作
对于(d=0;d<(元素总数);d++)
{
coutsizeof
运算符返回一个size\u t
值,这是一个无符号整数类型,因此在此循环中:
for(d=-1; d < (TOTAL_ELEMENTS);d++)
for(d=-1;d<(元素总数);d++)
-1
被转换为一个非常大的无符号整数值。另一个原因是您应该始终使用-Wall进行编译。(“警告:有符号和无符号整数表达式之间的比较”)(我认为VC++等价于/Wall)。