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

  • A+
Category:Languages

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 comes 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.

Comment

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