310 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.4k
views
1 answers
5 votes
Shefali asked Sep 11, 2015
1,410 views
Which of the following is not a recursive language?a. Regular languageb. {$\langle M,w \rangle$ | $M$ is a DFA that accepts $w$}c. {$\langle M \rangle$ | $M$ is a TM ... steps}d. {$\langle M \rangle$ | $M$ is a TM and $L(M)$ is regular }
469
views
0 answers
1 votes
Akshay Nair asked Jan 29, 2018
469 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 0c)1 -1 -1 -1 0d)1 -1 -1 1 2
330
views
1 answers
1 votes
Sandeep Suri asked Oct 26, 2017
330 views
Is the language ( )* regular? True or false explain with reason?
1.2k
views
1 answers
1 votes
kaveeshnyk asked May 7, 2019
1,179 views
#include<stdio.h> int main(){ int (*a)[5]; int arr[5][5]={ {10,65,300,400,500}, {100,20,3000,40,5000} }; a = arr; ++a ; char *ptr = (char*)*a; ++a ; printf("%d %d %d",**a,*arr[1],*ptr); return 0; }