How would you set a variable to the largest number possible in C?

Another portable way to get maximum value of integer:

Unsigned integer

unsigned int uMax = (unsigned int)~0;

Signed integer

signed int iMax = (unsigned int)~0 >> 1;

Explanation

  • ~0 -> setting all bits to one
  • >> 1 -> erasing sign bit, by shifting all bits to the right by one position
  • (unsigned int) typecasting to unsigned int after bits inversion instead of using ~0U, because C doesn't have a suffix for short,char literals (everything smaller than int in general)

So for biggest possible char value - just change in formula typecasting to unsigned char and etc.

Bonus - minimum value of signed int

Simply just invert all bits once more in max signed int expression:

signed int iMin = ~((unsigned int)~0 >> 1);

That sets first sign bit to one and the rest bits - to zero


#include <limits.h>
int x = INT_MAX;

EDIT: answered before the questioner clarified, I was just guessing what type they wanted.


There is a file called limits.h (at least on Linux there is), which holds this kind of definition e.g.

/* Maximum value an `unsigned short int' can hold.  (Minimum is 0.)  */
#  define USHRT_MAX 65535

/* Minimum and maximum values a `signed int' can hold.  */
#  define INT_MIN   (-INT_MAX - 1)
#  define INT_MAX   2147483647

/* Maximum value an `unsigned int' can hold.  (Minimum is 0.)  */
#  define UINT_MAX  4294967295U

Tags:

C

Integer

Limits