Thread: Writing a macro to compare two numbers?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by RichSelian View Post
    I want such a macro in my project: cmp(x, y) returns a positive number when x > y, a negative number when x < y, and 0 when x == y. of course I know the simplest way:
    Code:
    #define cmp(x, y) (((x) > (y)) ? 1 : (((x) == (y)) ? 0 : -1))
    but this cannot work properly for the code like cmp(x++, y++). Can this limit be fixed?
    Do you really care if it returns 1, 0 or -1? If all you care about is a positve, 0 or negative value you can simply return (x - y);
    Code:
    #define cmp(x, y) (x - y)

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by CommonTater View Post
    Do you really care if it returns 1, 0 or -1? If all you care about is a positve, 0 or negative value you can simply return (x - y);
    Code:
    #define cmp(x, y) (x - y)
    That won't work if x and y are both of unsigned integral type.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by grumpy View Post
    That won't work if x and y are both of unsigned integral type.
    Picky picky picky!

    But you're right it won't work on unsigned values...
    But then it was only an example, intended to convey an idea...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. writing a pair of numbers to an array
    By wankel in forum C Programming
    Replies: 53
    Last Post: 06-22-2009, 05:27 PM
  2. Writing unique numbers to an array
    By yardy in forum C Programming
    Replies: 6
    Last Post: 12-27-2006, 09:15 PM
  3. Writing a series of 8-bit numbers to disk with fwrite
    By thetinman in forum C Programming
    Replies: 16
    Last Post: 10-13-2006, 09:05 AM
  4. Help Writing My Own String Compare
    By djwicks in forum C Programming
    Replies: 4
    Last Post: 04-07-2005, 09:44 PM
  5. Replies: 2
    Last Post: 09-11-2002, 05:00 PM