On Tue, Jul 12, 2005 at 05:54:00PM +0100, Dave Korn wrote: > ----Original Message---- > >From: Daniel Berlin > >Sent: 12 July 2005 17:33 > > >> I think that even if the use of relational operators other than '==' and > >> '!=' is legal with pointers, the compiler should issue a warning (when > >> the option -Wall is used), as it does for assignment, used as truth > >> values, not surrounded with parentheses. > > > > Why? > > It's legal, it's useful, and used. > > > > --Dan > > > Just to enlarge upon Dan's comment: > > Since pointer subtraction is well defined, and it returns an int, then ... > > int *a, *b; > > if (a < b) > dosomething (); > > ... is just the same as ... > > int *a, *b; > > if ((b - a) >= 0) > dosomething (); > > ... so do you think the compiler should warn about _all_ pointer arithmetic?
Pointer subtraction is only well defined if both pointers point to elements in the same array (or one past the end of the array). Otherwise the behaviour is undefined. Relational operators between pointers are only defined if both pointers either point to elements in the same array (or one past the end of the array), or to members of the same structure. Otherwise the result is undefined. Thus, if you have code like: int aa,bb; int *a, *b; a=&aa; b=&bb; Then expressions like "(a>b)" or "(a-b)" both have undefined behaviour, while if you had code like int aa[2]; int *a, *b; a=&(aa[0]); b=&(aa[1]); Then the expressions "(a>b)" and "(a-b") are both well defined (and will have the values 0 and 1 respectively.) If the compiler is certain that the pointers do not point into the same array or structure (as in my first example above) it is probably a good idea to give a warning, but it should not warn for the legal cases (as in my second example.) -- <Insert your favourite quote here.> Erik Trulsson [EMAIL PROTECTED]