c++ - maximum value of int

ID : 20418

viewed : 118

Tags : c++cstllimitsnumeric-limitsc++c

Top 5 Answer for c++ - maximum value of int

vote vote


In C++:

#include <limits> 

then use

int imin = std::numeric_limits<int>::min(); // minimum value int imax = std::numeric_limits<int>::max(); 

std::numeric_limits is a template type which can be instantiated with other types:

float fmin = std::numeric_limits<float>::min(); // minimum positive value float fmax = std::numeric_limits<float>::max(); 

In C:

#include <limits.h> 

then use

int imin = INT_MIN; // minimum value int imax = INT_MAX; 


#include <float.h>  float fmin = FLT_MIN;  // minimum positive value double dmin = DBL_MIN; // minimum positive value  float fmax = FLT_MAX; double dmax = DBL_MAX; 
vote vote


I know it's an old question but maybe someone can use this solution:

int size = 0; // Fill all bits with zero (0) size = ~size; // Negate all bits, thus all bits are set to one (1) 

So far we have -1 as result 'till size is a signed int.

size = (unsigned int)size >> 1; // Shift the bits of size one position to the right. 

As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.

As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.

cout << size << endl; // Prints out size which is now set to maximum positive value. 

We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.

vote vote


#include <climits> #include <iostream> using namespace std;  int main() {   cout << INT_MAX << endl; } 
vote vote


Here is a macro I use to get the maximum value for signed integers, which is independent of the size of the signed integer type used, and for which gcc -Woverflow won't complain

#define SIGNED_MAX(x) (~(-1 << (sizeof(x) * 8 - 1)))  int a = SIGNED_MAX(a); long b = SIGNED_MAX(b); char c = SIGNED_MAX(c); /* if char is signed for this target */ short d = SIGNED_MAX(d); long long e = SIGNED_MAX(e); 
vote vote


Why not write a piece of code like:

int  max_neg = ~(1 << 31); int  all_ones = -1; int max_pos = all_ones & max_neg; 

Top 3 video Explaining c++ - maximum value of int