Google 그룹스는 더 이상 새로운 유즈넷 게시물 또는 구독을 지원하지 않습니다. 과거의 콘텐츠는 계속 볼 수 있습니다.

code not working properly

조회수 0회
읽지 않은 첫 메시지로 건너뛰기

Madhav

읽지 않음,
2005. 6. 23. 오전 7:52:0705. 6. 23.
받는사람
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

읽지 않음,
2005. 6. 23. 오전 8:23:1605. 6. 23.
받는사람

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

읽지 않음,
2005. 6. 23. 오전 8:25:2005. 6. 23.
받는사람

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

읽지 않음,
2005. 6. 23. 오전 8:28:0505. 6. 23.
받는사람
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

읽지 않음,
2005. 6. 23. 오전 8:22:4205. 6. 23.
받는사람
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개