隐式铸造到size_t?

发布于 2025-01-21 03:41:43 字数 183 浏览 2 评论 0原文

我想知道 - 当我们以某种值初始化unsigned size_t时,c ++是否会进行隐式铸造? 这样:

size_t value = 100;

在这样的阵容中添加“ u”字面的文字是有意义的吗?

size_t value = 100u;

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

椵侞 2025-01-28 03:41:43

当我们使用某些参数初始化 unsigned size_t 时,C++ 是否会进行隐式转换?
价值?像这样:

size_t 值 = 100;

是的。 std::size_t 是整数类型(的别名)。整数类型可以隐式转换为所有其他整数类型。

像这样向值添加“u”文字以防止这种转换是否有意义?

由于 std::size_t 不一定(也不通常)unsigned int,因此仍然可能存在带有 u 文字后缀的隐式转换。例如,它可以是unsigned long intunsigned long long int。有一项标准建议为 std::size_t 别名添加整数文字,但目前尚不存在。

在此示例中,使用匹配的文字并不重要,只要文字的类型可以表示所讨论的值,并且只要文字值不超出初始化类型的范围。即使是最小的整数类型也可以表示 100。选择很大程度上取决于个人喜好。


请注意,“隐式转换”是一个矛盾的术语。 Cast 是显式转换。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文