JASON
JASON

Reputation: 7491

adding two bool values in c/c++

I tried to add bool value together, say:

bool i = 0, j = 0, k = 0;
cout << sizeof(i + j + k) << endl;

The result is 4, which means, the result is converted to a 'int' value.

I want to ask: Is this a C/C++ standard operation? does the compiler always guarantee that the temporary value to be converted to a larger type if it overflows? Thanks!

Thanks for the answers, one follow up question: say, if I do: unsigned short i = 65535, j = 65535; cout << sizeof(i + j) << endl; The result is 4. Why it's been promoted to 'int'?

Upvotes: 14

Views: 19878

Answers (2)

Carl Norum
Carl Norum

Reputation: 224982

It's not the overflow that causes the conversion, it's the very fact you did arithmetic at all. In C++ (and C where the behaviour originated), the operands of basic arithmetic operators on built-in types go through a set of well-defined promotions before the calculation is made. The most of basic of these rules (somewhat simplified) is that any type smaller than an int gets promoted to int.

Your followup question has the same answer - your short is smaller than an int, so it gets promoted to an int before the addition takes place.

This StackOverflow question has several answers that describe the promotions in more detail.

Upvotes: 24

celtschk
celtschk

Reputation: 19721

First, sizeof doesn't tell you that the result is converted to an int value. It is allowed, and indeed not uncommon, that bool has the same size as int.

However you will indeed get an int here, but that's unrelated to the values (indeed, the type cannot depend on the values because in general the values will not be known until runtime, while the type must be determined at compile time).

What happens is that before adding, the bool values get promoted to int because bool is defined as an integer type, and integer types smaller than int all get promoted to int. You then add three int values (an operation which doesn't overflow no matter what bool values you use, because INT_MAX is guaranteed to be larger than 3).

Upvotes: 2

Related Questions