int*unsigned int = unsigned?

C

ciccio

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
 
J

Jonathan Lee

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top