...

/

Discussion: Aristotle’s Sum of Parts

Discussion: Aristotle’s Sum of Parts

Executed code to understand the output and gain insights into type promotion and usual arithmetic conversions.

Run the code

Now, it’s time to execute the code and observe the output.

Press + to interact
#include <iostream>
#include <type_traits>
int main()
{
char char1 = 1;
char char2 = 2;
// True if the type of char1 + char2 is char
std::cout << std::is_same_v<decltype(char1 + char2), char>;
}

Understanding the output

This is supposed to be a fun course, but sometimes, we need to talk about sad topics like this.

As we’ve figured out by now, the type of char + char is unfortunately not char. So what is it, then?

Binary operations in C++

For many binary operations, such as +, -, *, /, >, ==, ^, and more, the operands must be of the same type. We don’t have to ensure that ourselves, though; C++ will take care of it. C++ is, in fact, very eager to implicitly convert between types when we’re not looking, and this is one of the more confusing cases. Meet the usual arithmetic conversions.

Usual arithmetic conversions

The usual arithmetic conversions are performed on the operands to these operators to ensure both operands are of the same type. This common type is also the type of the result. For instance, if we add a float and an int, the int is first converted to a float, and the result is a float. If we add a float and a double, the float is first converted to a double, and the result is a double. It makes sense so far.

Confusion with integer types

The confusion starts when both operands are of integer types, especially if they are of the same type. For instance, if we add a char and an int, the char is first converted to an int, and the result is an int. It still makes sense. But what if we add a char and a short? Rather than converting the char to a short, both operands are converted to an int. And it gets worse: if we add two char types, which are already of the same type, they’re still converted to a different type!

Integral promotions

Let’s see what the usual ...