Defning SIZE_MAX

本文详细解析了在C语言中如何使用宏定义MY_SIZE_MAX来表示size_t类型的最大值。通过对表达式的逐步拆解,解释了为什么通过将-1转换为size_t类型可以得到该类型的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.velocityreviews.com/forums/t658743-defning-size_max.html

 

#define MY_SIZE_MAX ((size_t)-1)

(ozbear) writes:
> In another thread related to size_t and SIZE_MAX, a #define
> was suggested for SIZE_MAX where is it not predefined.
>
> The #define was:
>
> #define MY_SIZE_MAX ((size_t)-1)
>
> I have tried this on my system in a printf and it yields a
> reasonable value but I do not fully understand how it it
> evaluated. size_t is a /type/, defined on my system as
>
> typedef unsigned int size_t;
>
> The part I do not understand is the the meaning of subtracting 1
> from a /type/ rather than an expression? How does the compiler
> evaluate this?


As Ian Collins already posted, it's a cast, not a subtraction.

Looking at the expression in painful detail from the inside out:

``1'' is an integer constant.

``-1'' is an expression consisting of a unary "-" applied to ``1''.
It's value is -1, and its type is int.

``(size_t)-1'' is a cast expression, specifying that the result of the
expression ``-1'' is to be converted to type size_t. Given the the
rules for converting a signed int value to an unsigned type, the
result is the maximum value of type size_t.

Finally, we put parentheses around the whole thing because it's a
macro definition.

--
Keith Thompson (The_Other_Keith) kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值