conversion from unsigned

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lars Amsel

    conversion from unsigned

    Hi,

    I am a bit confused about some C++ code

    unsigned l = 1;
    cout << -l << " " << pow(2., -l-1.) << endl;

    I expected

    $>-1 0.25

    I got

    $>4294967295 inf

    OK. It's clear that their is a underflow in the unsigned l. I expected a
    auto conversion by the compiler to int. When I change the code to

    unsigned preL = 1;
    int l = -preL;
    cout << -l << " " << pow(2., -l-1.) << endl;

    everything works fine. Is that well defined c++ behaviour or is it a bug
    in g++ (version 3.3.x)?

    Cheers

    Lars
  • Rob Williscroft

    #2
    Re: conversion from unsigned

    Lars Amsel wrote in news:c6bg2g$9l7 ne$1@ID-95365.news.uni-berlin.de in
    comp.lang.c++:
    [color=blue]
    > Hi,
    >
    > I am a bit confused about some C++ code
    >
    > unsigned l = 1;
    > cout << -l << " " << pow(2., -l-1.) << endl;
    >
    > I expected
    >
    > $>-1 0.25
    >[/color]

    Basic arithmatic in C++, dosen't do type conversion's so
    -(ubsigned)1, has type unsigned, if nessacery the compiler
    will "widen" types *bofore* doing the arithmatic:

    long l = 1; int i = 2;

    ( l + i ) will have type long and before the addition i will
    be "widend" from int to long.

    unsigned int is "wider" than int, there is no real logic to it
    but one has to be wider than the other, else we wouldn't have
    a clue whats going on.
    [color=blue]
    > I got
    >
    > $>4294967295 inf[/color]

    (unsigned)-1 is required to be UINT_MAX (4294967295U on your
    platform).
    [color=blue]
    >
    > OK. It's clear that their is a underflow in the unsigned l.[/color]

    Nope unsigned uses modulo arithmatic, values wrap around from
    0 to UINT_MAX ( math is done modulo (UINT_MAX + 1) ).
    [color=blue]
    > I expected a
    > auto conversion by the compiler to int. When I change the code to
    >
    > unsigned preL = 1;
    > int l = -preL;
    > cout << -l << " " << pow(2., -l-1.) << endl;
    >
    > everything works fine. Is that well defined c++ behaviour or is
    > it a bug in g++ (version 3.3.x)?
    >[/color]

    Its well defined (other than the actual value 4294967295 (UINT_MAX)
    is implemetation defined).

    Rob.
    --

    Comment

    Working...