303 views
1 votes
1 votes

In this program the TOTAL_ELEMENTS calculates properly when not used in for loop. And the first printf prints properly.

But why the 2nd printf is not working even if the condition in the loop is true. TOTAL_ELEMENTS returns 7.

And -1<7-2 i.e -1<5 is true. 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;
}

1 Answer

Best answer
5 votes
5 votes

Due to implicit type casting.

When we operate on two different data types, the smaller one is implicitly casted to bigger one. And between signed and unsigned, unsigned is ranked higher. 

http://gatecse.in/wiki/Chapter_2:_Data_Types_and_Operators_in_C#Implicit_Type_Conversion

In the definition of TOTAL_ELEMENTS, sizeof, returns unsigned int, and unsigned int divided by unsigned int returns unsigned int. When compared with d, an integer, d is promoted to unsigned and becomes  2n-1, where n is the number of bits used for storing an int. So, the comparison here returns false. 

selected by

Related questions

1 votes
1 votes
0 answers
2
Akshay Nair asked Jan 29, 2018
454 views
What is the output of the following program?void main(){printf("%d",5%2);printf("%d",-5%2);printf("%d",5%-2);printf("%d",-5%-2);printf("%d",2%5);}A) 1,-1 -1 1 0B)1 -1 1 -...
1 votes
1 votes
1 answer
3
1 votes
1 votes
1 answer
4