Why does #define not run in a loop?

This program TOTAL_ELEMENTScomputes correctly if not used in a for loop. And the first printf prints correctly. But why does the second printf not work, even if the condition in the loop is true. TOTAL_ELEMENTSreturns 7. And -1<7-2ie -1<5true. So what is wrong here?

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};

int main()
{
int d;
printf("Total= %d\n", TOTAL_ELEMENTS);
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
+4
source share
3 answers

The problem is that it sizeofreturns a value unsigned. Therefore the whole expression

TOTAL_ELEMENTS-2

unsigned. , , , d <= (TOTAL_ELEMENTS-2) . -1 in unsigned , <= false .

, :

for(d=-1;d <= (int)((TOTAL_ELEMENTS)-2);d++)

+8

:

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};

int main()
{
 int d;
 printf("Total= %d\n", TOTAL_ELEMENTS);
 for(d=-1;d <= ((int)TOTAL_ELEMENTS-2);d++)
 {
   printf("%d\n",array[d+1]);
  }
 return 0;
  }

TOTAL_ELEMENT . .

0

TOTAL_ELEMENTS - , .

-3

Source: https://habr.com/ru/post/1568530/


All Articles