简体   繁体   English

如何在C中将size_t转换为int?

[英]How to convert size_t to int in C?

Is it possible to safely convert a variable with type size_t to type int in C99?是否可以在 C99 中将size_t类型的变量安全地转换为int类型?

I appreciate that size_t in unsigned, but in the case where we need an int representation, what can we do?我很欣赏 unsigned 中的size_t ,但在我们需要int表示的情况下,我们能做什么?

Is it possible to safely convert a variable with type size_t to type int in C99?是否可以在 C99 中将 size_t 类型的变量安全地转换为 int 类型?

It depends on what you mean by "safely".这取决于您所说的“安全”是什么意思。

The maximum representable value of type size_t is typically larger than the maximum representable value of type int . size_t类型的最大可表示值通常大于int类型的最大可表示值。 If you are asking whether all size_t values can be converted to type int without losing information then the answer is probably "no" for your implementation, and definitely "no" in a portability sense.如果您问是否可以将所有size_t值转换为int类型而不会丢失信息,那么您的实现的答案可能是“否”,并且在可移植性意义上绝对是“否”。

If you are asking whether it is possible to detect that a size_t value is too large for type int without actually trying to perform an explicit conversion, so as to avoid the implementation-defined result and possible signal in the event that the value is out of range and fall back to some kind of graceful failure, then the answer is "yes".如果您询问是否可以在不实际尝试执行显式转换的情况下检测到一个size_t值对于类型int来说太大,以避免该值超出范围时出现实现定义的结果和可能的信号范围并退回到某种优雅的失败,那么答案是“是”。 You can safely compare the value in question with INT_MAX .您可以安全地将相关值与INT_MAX进行比较。 Suitable value-preserving conversions will be applied automatically to bring the operands of the <= or > operator to a common type, and the operation will yield the appropriate result.将自动应用适当的保值转换,以将<=>运算符的操作数变为通用类型,并且该操作将产生适当的结果。

I appreciate that size_t in unsigned, but in the case where we need an int representation, what can we do?我很欣赏 unsigned 中的 size_t,但在我们需要 int 表示的情况下,我们能做什么?

If you're just asking about syntax, assuming that the values you want to convert will always be representable as type int , then you can cast ( int x; x = (int) my_size_t_value; ), but you don't actually need to do anything at all in some contexts.如果您只是询问语法,假设您要转换的值始终可以表示为int类型,那么您可以int x; x = (int) my_size_t_value; ( int x; x = (int) my_size_t_value; ),但实际上并不需要在某些情况下做任何事情。 In particular, you can directly assign a size_t to an int variable, or directly pass it to an int parameter of a non-variadic function with an in-scope prototype, and in those cases the appropriate conversion will be performed automatically.特别是,您可以直接将size_t分配给int变量,或将其直接传递给具有范围内原型的非可变参数函数的int参数,在这些情况下,将自动执行适当的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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