I'm quite new to C++ but I find this behaviour of auto
weird:
class A{};
int main() {
A a;
auto x = -(sizeof(a));
cout << x << endl;
return 0;
}
Variable x is unsigned
in this case although I used the unary minus operator at the initialiation of the variable. How come that only the return type of sizeof
(std::size_t
) is considered but not the fact that the stored number will be negative because of the used operator?
I'm aware of size_t
being an unsigned int.
I've tried this with GCC 8.1.0 and C++17.
cout << -(sizeof(a)) << endl;
. This has zero to do with auto. – Rockribbedauto
does not only respect the return type but do some kind context check like checking for unary minus operator or whatever happens in whole initialization process. – Despondent-
to be valid on unsigned values. Personally I would have rendered it invalid. – Firecureauto
it does not add anything new to the C++ language, it uses the very same mechanism that was already present in the language for template argument type deduction – Rockribbed0u - x
, you can get the same effect as-x
. Perhaps I would even forbid mixing signedness/unsignedness in operator expressions. IMO it could be useful to still allow-1u
.. so I could add a rule that unary minus on unsigned is only allowed on unsigned literals, which kind-of is similar to forbidding mixing of signedness in operator expressions. – Firecure0
being the exception. – Firecure- sizeof a
demonstrates the behaviour just as effectively. – Driblet