Issue
In the following example, gcc produces an int32_t
for the expression (-i)
. Even if I change the expression to (zero-i)
(with static constexpr int16_t zero = 0
), the expression remains a 4-byte int32_t
. What is the logic here?
#include <iostream>
int
main()
{
int16_t i = 4;
std::cout << "sizeof(i): " << sizeof(i) << std::endl;
std::cout << "sizeof(-i): " << sizeof(-i) << std::endl;
return 0;
}
Expected:
sizeof(i): 2
sizeof(-i): 2
but got:
sizeof(i): 2
sizeof(-i): 4
Solution
What is the logic here?
The logic is in the C++ standard (e.g. C++11 5.3.1:7) (C standards has equivalent clauses):
The operand of the unary - operator shall have arithmetic or unscoped
enumeration type and the result is the negation of its operand.
Integral promotion is performed on integral or enumeration operands
and 4.5:1
A prvalue of an integer type other than bool, char16_t, char32_t, or
wchar_t whose integer conversion rank (4.13) is less than the rank of
int can be converted to a prvalue of type int if int can represent all
the values of the source type; otherwise, the source prvalue can be
converted to a prvalue of type unsigned int.
According to the above i
is promoted to int
before unary minus is applied to it and the result of -i
expression is also int
.
Answered By - jcmvbkbc Answer Checked By - Willingham (WPSolving Volunteer)