14

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'?

JASON
  • 7,371
  • 9
  • 27
  • 40

2 Answers2

24

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.

Community
  • 1
  • 1
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

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).

celtschk
  • 19,311
  • 3
  • 39
  • 64
  • Yeah, if you count wrist watches and the gazillion other embedded 8bit micro-controllers. I reckon on all modern compilers and platforms I've seen it is a single byte. So a bool can be the size of an int only on 8 bit platforms. – dtech Jun 18 '13 at 22:29
  • 1
    Even on an 8-bit micro, `int` has to be at least 16 bits. I'd guess even there they're not the same size. – Carl Norum Jun 18 '13 at 22:36
  • 1
    @ddriver: The point is not that `int` might be 8 bit (it can't), but that `bool` may be larger than one byte. And that's not only a theoretical issue: http://stackoverflow.com/a/6935286/1032073 – celtschk Jun 19 '13 at 07:10