0
int b[5] = {1,2,3,4,5};
int *s = &b[0];
int *p = &b[1];
int *q = &b[2];
int *r = &b[2];

My question is when I compare p < q < r using if( p < q < r), I got the warning message.

What I thought is, first of all, (p < q) == True, so it's impossible to compare boolean with integer( address value of r). However, when True is considered as integer, it's 1. Right? So, 1 < r might make sense, in my guess.

What's wrong with my thought?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
PrinterPaper
  • 11
  • 1
  • 2
  • 4
    Please post your comparison code. – synchronizer Feb 20 '17 at 02:53
  • Don't you want to compare the integers instead of the memory addresses? – tkausl Feb 20 '17 at 02:54
  • 3
    "So 1 < r might make sense I guess." The compiler disagrees with you. – Raymond Chen Feb 20 '17 at 02:54
  • 1
    Are you dereferencing pointers OR just comparing pointers? Please share the exact code for more clarity. – Milind Deore Feb 20 '17 at 02:56
  • you didn't post the main part of the problem, but it's probably a duplicate of [Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?](http://stackoverflow.com/q/8889522/995714), [Language support for chained comparison operators (x < y < z)](http://stackoverflow.com/q/4090845/995714), [Why does (0 < 5 < 3) return true?](http://stackoverflow.com/q/4089284/995714) – phuclv Feb 20 '17 at 02:59
  • C does not define comparison between pointers and integers – M.M Feb 20 '17 at 03:20

3 Answers3

2

1 < r doesn't work because 1 is an integer and r is a pointer. Thus the warning.

My guess is you (a) meant to dereference the pointers, and (b) need to replace the chained comparisons with &&.

if (*p < *q && *q < *r)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

You seem to be under the impression that the expression p < q < r translations to "p is less than q, q is less than r", which would be typical of a mathematical notation.

However, the C programming language doesn't necessarily follow mathematical conventions. What p < q < r actually translations to is p < q, which might be 0 or 1 depending upon whether that's false or true, followed by either 0 < r or 1 < r based on that previous difference.

As another user has pointed out, the proper way to write "p is less than q and q is less than r" is p < q && q < r.

autistic
  • 1
  • 3
  • 35
  • 80
0

Change your condition from:

if(p < q < r) {}

To:

if(p < q && q < r) {}
Haze
  • 195
  • 7