is this broken or what?

Chris Torek chris at mimsy.umd.edu
Mon Feb 5 20:28:57 AEST 1990


>>... what is the prescribed behavior of
>>        int i=MAXINT, j=(-MAXINT);
>>        if (i > j) printf ("foo");

The ANSI conformant C program

	#include <stdio.h>
	#include <limits.h>

	int main(void) {
		int i = INT_MAX, j = INT_MIN;
		if (i > j) printf("foo\n");
		return 0;
	}

must print `foo' (at least on a hosted implementation).

In article <90020407120313 at masnet.uucp> mark.levy at canremote.uucp (MARK LEVY)
writes:
>   I am not up on the ANSI standards that have been proposed, but as
>I recall, the K&R standard was 0 == FALSE and anything else == TRUE.

This is correct, but has nothing to do with the answer to the previous
question.

>>        unsigned int i;
>>        if (i >= 0) ...

>   The use of 2's complement will avoid any kind of problem of 
>positive or negative zero.  A compiler might flag an incompatible
>data type comparison here.  My guess is that if the high order bit
>in i is set, the expression will evaluate false, provided that it
>compiled.

Henry Spencer has already given a correct answer; there is no need for
a false one.  If the variable `i' has ever been set after being created,
the test will always succeed (so that the code given as `...' will be
executed), and indeed, a compiler is free not to generate any code at
all for the test, and to produce a warning.

>   Don't ever assume anything about type conversions.  If you're not
>sure, use pleanty of casts and parens.

If you have a compiler that claims to conform to the ANSI standard, you
can make any assumption that the ANSI standard says must hold.  If you
are working with older compilers, be wary; but in this case you need not
worry: all unsigned numbers are greater than or equal to zero.  The only
way for the code to fail is if i has never been assigned a value: in
such a case it might, e.g., have an `invalid value' type tag that causes
a run-time exception when tested.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list