Why size of QByteArray is `int` rather than `unsigned int`

  • A+
Category:Languages

I have such expressions in my code:

QByteArray idx0 = ...  unsigned short ushortIdx0;  if ( idx0.size() >= sizeof(ushortIdx0) ) {     // Do something } 

But I'm getting the warning:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

if ( idx0.size() >= sizeof(ushortIdx0) ) {               ~~~~~~~~~~~~^~~~~~~~~~ 

Why size() of QByteArray is returned as int rather than unsigned int? How can I get rid of this warning safely?

 


Some folk feel that the introduction of unsigned types into C all those years ago was a bad idea. Such types found themselves introduced into C++, where they are deeply embedded in the C++ Standard Library and operator return types.

Yes, sizeof must, by the standard, return an unsigned type.

The Qt developers adopt the modern thinking that the unsigned types were a bad idea, and favour instead making the return type of size a signed type. Personally I find it idiosyncratic.

To solve, you could (i) live with the warning, (ii) switch it off for the duration of the function, or (iii) write something like

(std::size_t)idx0.size() >= sizeof(ushortIdx0) 

at the expense of clarity.

Comment

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