Thread: Compare a double to an integer

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    16

    Compare a double to an integer

    Given this code
    Code:
    double x=1.00,y=2,z=4;
    if (y/z||++x)
          x+=y/z;
    printf("%f\n",x);
    So (y/z||++x) is true if at least one expression is true, that is either (y/z)!=0 or (++x)!=0 or both. I wonder how the comparison is done? Is (y/z) be truncated to integer or 0 be promoted to double?

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    In general, when mixing integers and doubles in an expression, the integers are promoted to doubles, but they are promoted only when necessary to evaluate a specific operation (all operations occur only on equal types).

    What I mean is, 1 / 3 + 0.1 will return a double, but it will do 1/3 as integer math first (since it's sooner in the order of operations), yielding 0, and then the addition happens. 0 is promoted to 0.0 and added to 0.1 to yield a final answer of 0.1
    Last edited by Cat; 02-24-2013 at 10:16 AM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    FYI the type promotion list is as follows:

    Long double
    Double
    Float
    Unsigned long int
    Long int
    Unsigned int
    Int

    When an operator has two differently typed operands, the lower operand on the list is promoted to be the same as the higher, even if there is the possibility to introduce errors (e.g. unsigned int - signed int does an unsigned operation.

    Any argument shorter than an int is automatically promoted to an int anyway when used in a mathematical expression, even if this is unnecessary for the argument type (e.g. short + short math is actually int + int math).
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compare double to 0 using DBL_EPSILON
    By stdq in forum C Programming
    Replies: 1
    Last Post: 05-13-2012, 06:10 PM
  2. compare pointer and integer?
    By nyekknyakk in forum C Programming
    Replies: 19
    Last Post: 08-19-2010, 10:19 PM
  3. how can i compare a string to an integer?
    By Huskar in forum C Programming
    Replies: 6
    Last Post: 03-31-2009, 01:13 PM
  4. How to convert an integer to double?
    By salman86 in forum C++ Programming
    Replies: 8
    Last Post: 07-07-2005, 06:39 PM
  5. compare double value to 0 - unreliable comparisons warning
    By collymitch in forum C Programming
    Replies: 3
    Last Post: 04-04-2005, 07:38 PM