简体   繁体   中英

Implicit cast to size_t?

I want to know - does C++ do implicit cast when we initialize unsigned size_t with some value? Like this:

size_t value = 100;

And does it make sense to add 'u' literal to the value to prevent this cast, like this?

size_t value = 100u;

does C++ do implicit cast when we initialize unsigned size_t with some value? Like this:

 size_t value = 100;

Yes. std::size_t is an (alias of an) integer type. An integer type can be implicitly converted to all other integer types.

And does it make sense to add 'u' literal to the value to prevent this cast, like this?

There is still likely an implicit conversion with the u literal suffix since std::size_t is not necessarily (nor typically) unsigned int . It may be for example unsigned long int or unsigned long long int . There is a standard proposal to add integer literal for the std::size_t alias, but there doesn't exist one for now.

Using a matching literal doesn't matter much in this example, as long as the type of the literal can represent the value in question, and as long as the literal value doesn't exceed the bounds of the initialised type. Even the smallest integer types can represent 100. The choice is largely a matter of taste.


Note that "implicit cast" is a contradiction in terms. Cast is an explicit conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM