#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
The above snippet doesnt print the array as expected.
I think the error is in the Test-condition in for loop.
If i cast it to INT [(int)TOTAL_ELEMENTS-2)] than its working fine.
y is it so..can sbd tell me what the return type of sizeof
is??
> int d;
> for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
>I think the error is in the Test-condition in for loop.
>If i cast it to INT [(int)TOTAL_ELEMENTS-2)] than its working fine.
>y is it so..can sbd tell me what the return type of sizeof
>is??
sizeof has type size_t . The exact width of size_t is unspecified,
but one thing that -is- specified about it is that it is unsigned.
You might be having difficulty with comparing a negative int
to an unsigned integral type.
--
"This was a Golden Age, a time of high adventure, rich living and
hard dying... but nobody thought so." -- Alfred Bester, TSMD
From K&R2, Section A6.5:
[automatic conversion of operands]
If either operand is unsigned int, the other is
converted to unsigned int.
Thus the -1 in d=-1 is converted (unsigned int)(-1) which
generally is a pretty large number.
--
Rouben Rostamian
sasiraj wrote:
> #include<stdio.h>
>
> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
> int array[] = {23,34,12,17,204,99,16};
>
> int main()
> {
> int d;
>
> for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
> printf("%d\n",array[d+1]);
>
> return 0;
> }
>
> The above snippet doesnt print the array as expected.
hello sasi
Do you want to print the array in order as it is declared?If yes they
are printing in order .
and if no then clarify in which order?
Try going through sizeof help and you would have the answer yourself.
> int array[] = {23,34,12,17,204,99,16};
>
> int main()
> {
> int d;
>
> for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
OR another choice could be to initialise d to 0. But I guess you did
not want this. Soo, go through sizeof help.
I dont think its should print the contents without you modifying the
#define preprocessor. Please check once again.
OR probably I need to check my compiler. ;)