question, about implicit conversions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mason Verger

    question, about implicit conversions

    Given:



    int center = 0;

    int range = 5;

    int lower = 0;

    What does this statement do? Is range converted to a float then divided by 2
    then casted back to int?

    center = ((range)/2) + lower;



  • Martin Ambuhl

    #2
    Re: question, about implicit conversions

    Mason Verger wrote:
    [color=blue]
    > Given:
    > int center = 0;
    > int range = 5;
    > int lower = 0;
    >
    > What does this statement do? Is range converted to a float then divided by 2
    > then casted back to int?[/color]

    No. range is an int, 2 is an int, so range/2 does integer division.
    [color=blue]
    > center = ((range)/2) + lower;[/color]
    range = 5
    range/2 = 5/2 = 2
    lower = 0
    (range/2) + lower = 2 + 0 = 2
    center = 2

    But with either of the following (or many other similar forms)
    (range/2.) + lower
    ((double)range/2) + lower
    the RHS is 2.5, and the assignment to an int now drops the fractional part.
    center becomes 2 in this case as well.





    --
    Martin Ambuhl

    Comment

    • Mike Wahler

      #3
      Re: question, about implicit conversions


      Mason Verger <mason_verger@s kincare.com> wrote in message
      news:iCS9b.515$ t93.345@nwrddc0 2.gnilink.net.. .[color=blue]
      > Given:
      >
      >
      >
      > int center = 0;
      >
      > int range = 5;
      >
      > int lower = 0;
      >
      > What does this statement do?
      >
      > center = ((range)/2) + lower;[/color]
      [color=blue]
      > Is range converted to a float[/color]

      No.
      [color=blue]
      >then divided by 2[/color]

      It's divided by two using 'integer division', which
      will truncate any remainder. I.e. range / 2 will
      give a result of 2.
      [color=blue]
      > then casted back to int?[/color]

      No conversions or casts are performed in your example.
      All your operands already have the same type.


      -Mike



      Comment

      Working...