Joseph Perez
Joseph Perez

Reputation: 118

Making the minimum integer value positive in C

So I've got the following code

printf("atoi(input) = %d\n", atoi(input));
long number = 0;
if(atol(input) < 0){
    printf("went into here\n");
    printf("atoi = %d\n", atoi(input)); 
    number = -1 * atoi(input);  
    printf("number = %d\n", number);    
}else{
    number = atoi(input);
}

But for some reason when my user inputs -2147483648 (and probably other really large decimals), the multiply by -1 doesn't work, and the number remains negative. Any ideas?

Upvotes: 0

Views: 384

Answers (3)

Hiren
Hiren

Reputation: 130

You are running into the value limit for a signed long integer. You will need to try using another data type.

Upvotes: 0

Brendan
Brendan

Reputation: 37262

For both atoi() and atol(); if the converted value is out of range for the return type (int and long int respectively), then you get undefined behaviour (e.g. "format hard drive").

To avoid undefined behaviour you must ensure that the value in the string is within a certain range before using either atoi() or atol().

Any technique that correctly ensures the value in the string is within a certain range (without using either atoi() or atol()) is also a technique that can be modified slightly and used to detect and handle the INT_MIN case (without using either atoi() or atol()).

Upvotes: 1

VolAnd
VolAnd

Reputation: 6407

Unfortunately memory allocated for any standard tipe is limited, so ranges of all all types have quite definite borders. Violated borders lead to computing errors.

To know borders (like min and max possible values) for integer types (not only int, but also char, short, etc.) you can use limits.h. E.g.:

#include <stdio.h>
#include <limits.h>

int main(void)
{
    printf("INT_MIN = %d\n", INT_MIN);
    printf("INT_MAX = %d\n", INT_MAX);
    printf("LONG_MIN = %ld\n", LONG_MIN);
    printf("LONG_MAX = %ld\n", LONG_MAX);
    printf("LLONG_MIN = %lld\n", LLONG_MIN);
    printf("LLONG_MAX = %lld\n", LLONG_MAX);
    return 0;
}

Note:

1) values of limits depends on compiler and platform (e.g. for my system LONG_MIN is equal to INT_MIN, but perhaps, you will see different values);

2) limits.h is just text file that can be oppend and explored

3) also learn about stdint.h, that provide types with fixed sizes (and allows programs to be portable without "perhaps" in my first note)

4) there are some techniques to detect integer overflow

Upvotes: 1

Related Questions