问题描述
我正在尝试在C89中获得SIZE_MAX
.
I'm trying to get SIZE_MAX
in C89.
我想到了以下找到SIZE_MAX
的方法:
I thought of the following way to find SIZE_MAX
:
const size_t SIZE_MAX = -1;
自该标准(第6.2.1.2节ANSI C)说:
Since the standard (§6.2.1.2 ANSI C) says:
带脚注28:
这似乎已经定义了行为,但是我不确定我是否正确理解该段落的措辞.
This seems like this has defined behavior, but I'm not quite sure if I understand the wording of that paragraph correctly.
请注意,此问题与C89有关,因此此不会回答我的问题,因为标准的措辞不同
Note that this question is explicitly about C89, so this doesn't answer my question because the standard has different wording.
如果这不起作用,我想出的另一种方法是:
If that doesn't work, the other way I came up with is:
size_t get_size_max() {
static size_t max = 0;
if (max == 0) {
max -= 1U;
}
return max;
}
但是我在标准中找不到关于无符号整数下溢的任何信息,所以我在这里摸索着.
But I couldn't find anything about unsigned integer underflow in the standard, so I'm poking in the dark here.
推荐答案
您可以使用:
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)(-1))
#endif
在C11 6.3.1.3节转换-有符号和无符号整数"中定义了将-1
转换为无符号整数类型的行为. C89具有等同的定义,编号为3.2.1.2.实际上,您在问题中引用了ISO C90定义6.2.1.2(ANSI C89和ISO C90之间的区别是各节的编号不同).
The behaviour of converting -1
to unsigned integer type is defined under section C11 6.3.1.3 "Conversions - Signed and unsigned integers". C89 had an equivalent definition, numbered 3.2.1.2. In fact you quoted the ISO C90 definition 6.2.1.2 in your question (the difference between ANSI C89 and ISO C90 is that the sections are numbered differently).
我不建议使用const
变量,因为它们不能在常量表达式中使用.
I would not recommend using a const
variable, since they cannot be used in constant expressions.
注意:这不能在C90预处理器算法中使用,该算法仅适用于不包含强制转换或单词的整数常量表达式,因此我们不能使用任何sizeof
技巧.在这种情况下,您可能需要特定于系统的定义;预处理程序没有标准的方法来检测typedef.
Note: This can't be used in C90 preprocessor arithmetic, which only works on integer constant expressions that contain no casts or words, so we can't use any sizeof
tricks. In that case you might need a system-specific definition; there's no standard way for the preprocessor to detect a typedef.
这篇关于如何在C89中获得SIZE_MAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!