Is there a function in C that returns the maximum value of a variable like this (I will name the function \"maxvalue\" in example below)?
int a;
printf(\"%d\", m
Such a function is not defined by the C standard library. You can try defining a macro that calculates it:
#define MAX_VALUE(a) (((unsigned long long)1 << (sizeof(a) * CHAR_BIT)) - 1)
When using it, be careful it is assigned to a type large enough. For example:
#include
#include
#include
#define IS_TYPE_SIGNED(a) ((a-1) < 0)
#define MAX_VALUE_UNSIGNED(a) (((unsigned long long)1 << \
(sizeof(a) * CHAR_BIT)) - 1)
#define MAX_VALUE_SIGNED(a) (MAX_VALUE_UNSIGNED(a) >> 1)
#define MAX_VALUE(a) (IS_TYPE_SIGNED(a) ? \
MAX_VALUE_SIGNED(a) : MAX_VALUE_UNSIGNED(a))
int main(void)
{
unsigned int i = 0;
signed int j = 0;
printf("%llu\n", MAX_VALUE(i));
printf("%llu\n", MAX_VALUE(j));
return EXIT_SUCCESS;
}
This prints out:
4294967295
2147483647