int*unsigned int = unsigned?

Discussion in 'C++' started by ciccio, Jun 4, 2010.

  1. ciccio

    ciccio Guest

    Why is the multiplication of an int with an unsigned int again unsigned?

    #include <iostream>
    #include <typeinfo>

    int main(void) {
    int a = 12;
    int b = -12;
    unsigned int c = 6;

    std::cout << a << " " << typeid(a).name() << std::endl;
    std::cout << b << " " << typeid(b).name() << std::endl;
    std::cout << a*b << " " << typeid(a*b).name() << std::endl;
    std::cout << a*c << " " << typeid(a*c).name() << std::endl;
    std::cout << b*c << " " << typeid(b*c).name() << std::endl;
    return 0;
    }

    The output gives

    ../a.out
    12 i
    -12 i
    -144 i
    72 j
    4294967224 j

    Regards
     
    ciccio, Jun 4, 2010
    #1
    1. Advertising

  2. ciccio

    Jonathan Lee Guest

    On Jun 4, 9:24 am, ciccio <> wrote:
    > Why is the multiplication of an int with an unsigned int again unsigned?


    ....because those are the rules. Specifically b*c is unsigned
    because of the "usual arithmetic conversions" (see [expr] in
    the standard.. item 9). Here you have an int times an
    unsigned int. The standard says that the int gets converted
    to an unsigned int to match. Then the multiplication is
    performed.

    As for why it is the way it is... I guess there's only a few
    sensible options, and this is the one they decided on.

    --Jonathan
     
    Jonathan Lee, Jun 4, 2010
    #2
    1. Advertising

  3. ciccio

    Öö Tiib Guest

    On Jun 4, 4:24 pm, ciccio <> wrote:
    > Why is the multiplication of an int with an unsigned int again unsigned?


    Because standard [Expr]/9 says so.
     
    Öö Tiib, Jun 4, 2010
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Timo Freiberger
    Replies:
    3
    Views:
    976
    Bob Hairgrove
    Oct 30, 2004
  2. Schnoffos
    Replies:
    2
    Views:
    1,236
    Martien Verbruggen
    Jun 27, 2003
  3. Hal Styli
    Replies:
    14
    Views:
    1,681
    Old Wolf
    Jan 20, 2004
  4. er
    Replies:
    6
    Views:
    500
    Andre Kostur
    Sep 14, 2007
  5. pozz
    Replies:
    12
    Views:
    762
    Tim Rentsch
    Mar 20, 2011
Loading...

Share This Page