开发者

API to check maximum value of any data type exceeded

开发者 https://www.devze.com 2023-02-24 11:30 出处:网络
Is there any API to check if any number exceeds it\'s range? My number is stored as string. char *ptr = \"123456789\"

Is there any API to check if any number exceeds it's range?

My number is stored as string. char *ptr = "123456789"

API should do: int a = api(ptr, long) if a==-1 suppose value exceeds.

Please note: We can't parse the string and check because it will automatically wrap it to the other side, and make it within the range.

开发者_开发技巧Thanks in advance


Please checkout strtol and strtoul.

See this example:

#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main (int argc, char const* argv[])
{
    char a[] = "123";
    char c[] = "123134123412341234";
    long b, d;
    errno = 0;
    b = strtol(a, NULL, 10);
    if((b == LONG_MAX || b == LONG_MIN) && errno == ERANGE ){
        printf("%s Out of range\n", a);
    }
    errno = 0;
    d = strtol(c, NULL, 10);
    if((d == LONG_MAX || d == LONG_MIN) && errno == ERANGE ){
        printf("%s Out of range\n", c);
    }
    return 0;
}

Edits:

  1. Changed int to long for b and d.
  2. Setting errno to 0 before calling into c library.
  3. Checking for LONG_MIN also for errors.
  4. Changed the order for checks (according to comment below)


Well, you can still check. Just build up the number and check to see if the number indeed became bigger or smaller.

int i = 0; // pos indicator
int r = 0; // result
int c = 0; // check
while(ptr[i])
{
    c = r;
    r = r * 10 + (ptr[i++] - '0');
    if(r < c)
        print("overflow happened!\n");
}

Edit: Note that this won't work with unsigned datatypes as it's too easy to overflow far enough to still pass the check.


Just use strol() or strtoll() and check errno. For smaller datatypes you need to make a very simple function that compares against USHRT_MAX, UINT_MAX etc from limits.h.

man strol and man limits.h for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消