如何在C89中获得SIZE_MAX [英] How to get SIZE_MAX in C89

查看:650
本文介绍了如何在C89中获得SIZE_MAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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

带脚注28:

在二进制补码表示中,如果无符号整数的大小较大,则除了用符号位的副本填充高阶位以外,位模式没有实际变化.

In a two's-complement representation, there is no actual change in the bit pattern except filling the high-order bits with copies of the sign bit if the unsigned integer has greater size.

这似乎已经定义了行为,但是我不确定我是否正确理解该段落的措辞.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆