C ++ maximum is not negative int

Are int sizes, etc., expected to work on all platforms as expected? Or is there a more acceptable way to do this? (I did the following.)

#define MAX_NON_NEGATIVE_INT ((int)(((unsigned int)-1) / 2))

I will not insult your intellect by explaining what it does!

Edit: I should have mentioned that I cannot use any standard classes because I run without C runtime.

0
source share
5 answers

If you do not want to use define (and you want a standard way to calculate limits), do the following:

#include <limits>
std::numeric_limits<int>::min()

This ANSI standard defines in limits.h:

#define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX       2147483647    /* maximum (signed) int value */
#define UINT_MAX      0xffffffff    /* maximum unsigned int value */

These are the definitions from BaseTsd.h:

#define MAXUINT     ((UINT)~((UINT)0))
#define MAXINT      ((INT)(MAXUINT >> 1))
#define MININT      ((INT)~MAXINT)
+7
source

There is a standard way to do this :

#include <limits>
#include <iostream>

cout << numeric_limits<unsigned int>::max();

, .

+11
#include <climits>


INT_MAX
0

numeric_limits, .

.

0

, , ++, C.

const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;

2, , -, MAXINT.

MAXINT , ,

#include <limits>
    const int OFFICIALMAXINT = numeric_limits<int>::max();

MININT gives the same thing as you, using

#include <limits>
    const int OFFICIALMININT = numeric_limits<int>::min();

Hard coding of these values, as mentioned above, is the idea of ​​Baaad.

I prefer to beat, because I know that he is always right, and I do not need to rely on remembering the library and the syntax of the call, but it depends on the preference.

0
source

Source: https://habr.com/ru/post/1653795/


All Articles