Don’t mix signed and unsigned types in C/C++

Assume that we have two variables a and b. a is unsigned and is int. What will be result of the expression when a will be equal to 1 and b to -1 (what will be an output of the following code):

#include <iostream>

int main(int argc, char ** argv)
	unsigned a = 1;
	int b = -1;

	std::cout << a * b;

	return 0;

See my output:


Suprised? This value depends on how many bits an int has on your (my in this case) machine.

Ok, next question: What will be the output now?

#include <iostream>

int main(int argc, char ** argv)
	int a = -1;
	unsigned b = 1;

	int c = a * b;

	std::cout << c;

	return 0;

The answer is:


Weird? I think that the best conclusion is the topic of this post.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s