Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

code not working properly

0 views
Skip to first unread message

Madhav

unread,
Jun 23, 2005, 7:52:07 AM6/23/05
to
Hi all,
I recently came across this small piece of code:

#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;
}

it does not print anything. the reson i think its not printing
anything because of the comparison returning false. Why is the
condition not true?
please help me with this problem.

mano...@gmail.com

unread,
Jun 23, 2005, 8:23:16 AM6/23/05
to

sizeof returns size_t which is unsigned. So (TOTAL_ELEMENTS-2) is
unsigned.
C converts d to unsigned before comparing.
-1 becomes a large number and condition became false.

Keith Thompson

unread,
Jun 23, 2005, 8:25:20 AM6/23/05
to

Here's a simplified example:

This program prints nothing:

#include<stdio.h>
int main(void)
{
int d;
size_t max = 5;
for(d = -1; d <= max; d ++) {
printf("d = %d\n", d);
}
return 0;
}

This one works:

#include<stdio.h>
int main(void)
{
int d;
int max = 5;
for(d = -1; d <= max; d ++) {
printf("d = %d\n", d);
}
return 0;
}

The problem is that TOTAL_ELEMENTS expands to an expression of type
size_t. When you apply an operator ("<=" in this case) to an int and
a size_t (an unsigned type), the int value is promoted to size_t.
Converting the value -1 to size_t yields a large positive value,
typically 2147483647 if size_t is 32 bits.

Casting TOTAL_ELEMENTS to int is one workaround (one of the few cases
where a cast isn't a bad idea).

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.

jacob navia

unread,
Jun 23, 2005, 8:28:05 AM6/23/05
to
sizeof(x) returns an UNSIGNED int. Then, the comparison with a signed int d
will be done in "unsigned" mode. The minus one will be transformed into
0xffffffff, in a 32 bit platform, yielding a huge number.

This huge number will be compared to 5, and the condition does not hold,
so nothing is printed and the program exits.

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

Note the (int) cast.

jacob

Grumble

unread,
Jun 23, 2005, 8:22:42 AM6/23/05
to
Madhav 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;
> }
>
> it does not print anything. the reson i think its not printing
> anything because of the comparison returning false. Why is the
> condition not true?

Hint: d is signed, TOTAL_ELEMENTS-2 is unsigned.

#include <stdio.h>
int main(void)
{
printf("%u\n", (unsigned)(-1));
return 0;
}

0 new messages