Is it safe to compare unsigned int with std :: string :: size_type parameter

I go through the book "Accelerated C ++" by Andrew Koenig and Barbara E. Mu, and I have some questions about the main example in chapter 2. The code can be summarized as shown below and compiled without warning / error using g ++:

#include <string>
using std::string;

int main()
{
    const string greeting = "Hello, world!";
    // OK
    const int pad = 1;
    // KO
    // int pad = 1;
    // OK
    // unsigned int pad = 1;
    const string::size_type cols = greeting.size() + 2 + pad * 2;
    string::size_type c = 0;
    if (c == 1 + pad)
    {;}

    return 0;
}

However, if I replaced const int pad = 1;with int pad = 1;, the g ++ compiler will return a warning:

warning: comparison between signed and unsigned integer expressions [-Werror=sign-compare]
    if (c == 1 + pad)

If I replaced const int pad = 1;with unsigned int pad = 1;, the g ++ compiler will not return a warning.

I understand why g ++ returns a warning, but I'm not sure of the following three points:

  • Can I use unsigned intto compare with std::string::size_type? The compiler does not return a warning in this case, but I'm not sure if it is safe.
  • const int pad = 1. pad unsigned int?
  • const int pad = 1; string::size_type pad = 1;, pad . , , ?
+4
4

:

  • ( ).
  • 2 .
  • , , (, 16- [0..32767]).

, :

  • , unsigned int std::string::size_type.
  • , ( :)).
  • . unsinged int.
+2

std::string ( ), size_type size_t.

[support.types]/6 , size_t

, , .

, unsigned int, , .

: const int something = 2, , a) b) , size_t. 2.

, size_type , -, .

+1

, , "" , , , ( , , , a > b true a = -1 b = 100. ( const int , , , ", 1, " )

, , unsigned int ( , 4 ) .

+1

, , . , , . , unsigned , , .

unsigned int std::string:: size_type? , , .

, , - , . , .

const int pad = 1. pad unsigned int?

, . . , , , , 1, .

const int pad = 1; by string:: size_type pad = 1;, pad . , , ?

If you don't want it to be permanent, the best solution would probably be to make it at least an unsigned integer type. However, you should be aware that there is no guaranteed relationship between normal integer types and sizes, for example, it unsigned intmay be narrower, wider or equal size_tand size_type(the latter may also differ).

+1
source

Source: https://habr.com/ru/post/1673273/


All Articles