How to get SIZE_MAX in C89

前端 未结 2 1084
悲哀的现实
悲哀的现实 2021-01-18 21:16

I\'m trying to get SIZE_MAX in C89.

I thought of the following way to find SIZE_MAX:

const size_t SIZE_MAX = -1;

2条回答
  •  后悔当初
    2021-01-18 21:38

    You could use:

    #ifndef SIZE_MAX
    #define SIZE_MAX ((size_t)(-1))
    #endif
    

    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).

    I would not recommend using a const variable, since they cannot be used in constant expressions.


    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.

提交回复
热议问题