This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: sizeof() function result tests < -1
- To: bug-gcc at gnu dot org, richard_sharman at Mitel dot COM
- Subject: Re: sizeof() function result tests < -1
- From: "Kaveh R. Ghazi" <ghazi at caip dot rutgers dot edu>
- Date: Fri, 7 Jan 2000 16:13:51 -0500 (EST)
> From: Richard Sharman <richard_sharman@Mitel.COM>
>
> On a sparc and a 386, although sizeof(int) returns 4 when used in an
> assignment, the test sizeof(int) < -1 returns true.
>
>
> % gcc -v
> Reading specs from /usr/local/lib/gcc-lib/sparc-sun-solaris2.6/2.8.1/specs
> gcc version 2.8.1
> % uname -a
> SunOS topaz 5.6 Generic_ sun4u unknown
> %
>
> % cat -n x.c
> 1 #include <stdio.h>
> 2
> 3 int main(void) {
> 4 int x;
> 5
> 6 /* This works as expected */
> 7 x = sizeof(int);
> 8 printf("%d\n", x);
> 9 if (x < -1) {
> 10 printf("x < -1\n");
> 11 } else {
> 12 printf("ok(1)\n");
> 13 }
> 14
> 15
> 16 /* This fails */
> 17 printf("%d\n", sizeof(int));
> 18 if (sizeof(int) < -1) {
> 19 printf("sizeof(int) < -1\n");
> 20 } else {
> 21 printf("ok(2)\n");
> 22 }
> 23
> 24
> 25 /* This, testing against 0, works as expected. */
> 26 printf("%d\n", sizeof(int));
> 27 if (sizeof(int) < 0) {
> 28 printf("sizeof(int) < 0\n");
> 29 } else {
> 30 printf("ok(3)\n");
> 31 }
> 32
> 33 exit(0);
> 34 }
> % gcc -Wall -o x x.c && ./x
> 4
> ok(1)
> 4
> sizeof(int) < -1
> 4
> ok(3)
> %
Try compiling with -Wsign-compare, it'll hint at the problem.
What's going on is that the sizeof() directive is unsigned on your
system. Your comparison is essentially (4U < -1). The promotion
rules will convert -1 to unsigned which then becomes a very large
positive number, and greater than 4.
--Kaveh
--
Kaveh R. Ghazi Engagement Manager / Project Services
ghazi@caip.rutgers.edu Qwest Internet Solutions