Marlene Stebbins <ma*****@mail.com> writes:
I am entering numbers into my program from the command line. I want to
check whether they are > INT_MAX. Sounds simple, but I've discovered
that
if(x <= INT_MAX)
{
/* use x in some calculation */
}
else
{
/* exit with error message */
}
doesn't work! And, after thinking about it a little bit, it makes
sense that it doesn't work because if x is bigger than INT_MAX
(whatever that might be on a particular implementation) it just gets
clobbered into something that is garbage before it ever gets to my
test. Is there a way to use INT_MAX to check for overflow? How would
you best deal with this problem generally?
It's hard to tell, since you don't show us how x gets its value. The
checking needs to occur in the code that you didn't post.
If you use something like atoi(argv[i]) to convert a command-line
argument to an int, it won't do any error checking. You can use the
strtol() function, which returns a long int and does error checking if
you give it the right arguments. You'll need to use strtol()'s own
error checking mechanism and check whether the long result fits in an
int. Something like this:
long result = strtol(argv[i], blah, 10);
if (/* strtol indicates an error*/) {
/* error */
}
else if (result > INT_MAX) {
/* overflow */
}
else if (result < INT_MIN) {
/* underflow */
}
else {
/* You have a valid int value */
}
I'm too lazy to look up the details of how to use strtol(); you should
have documentation that will tell you everything you need to know.
Remember that strtol() converts the initial portion of its string
argument, so if you give it "123xyz", it will give you 123. Decide
whether to treat this as an error (strtol() can tell you whether it
converted the entire string or just an initial substring).
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.