Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding two bool values in c/c++

Tags:

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

like image 613
JASON Avatar asked Jun 18 '13 21:06

JASON


1 Answers

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.

like image 52
Carl Norum Avatar answered Sep 17 '22 15:09

Carl Norum