Why does 'auto' not respect the unary minus operator?

  • A+

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.


The actual issue here is that use of unary minus operator, just like the rest of built-in arithmetic operators, is a subject to integral promotions. So surprisingly the result of applying unary minus to size_t will be still size_t and there is no need to blame auto.

Counter-example. In this case due to integral promotions type of x will be int so output will be -1:

unsigned short a{1}; auto x{-a}; cout << x << endl; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: