size_t num = 0 这样写对吗?

Is it correct to write size_t num = 0?

我正在编写一个 C 程序,其中我使用 size_t 来存储数值,因为在互联网上它说 size_t 只能存储 unsigned 值。

所以可以在其中存储 0 吗??

size_t num = 0;

是的,没问题。

C17 6.7.9 (11):

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

6.3.1.3 (1) 说:

When a value with integer type is converted to another integer type other than _Bool , if the value can be represented by the new type, it is unchanged.

0int 类型的表达式,其值为数字零。值零当然可以用 size_t 表示,因此它被初始化为。

如果你更喜欢符号匹配,你可以写size_t num = 0U;,但它的效果是一样的。