Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!usc!apple!sun-barr!decwrl!shelby!csli!poser From: poser@csli.Stanford.EDU (Bill Poser) Newsgroups: comp.lang.c Subject: Re: Is There A Way To Check If argv[1] Is An Integer? Message-ID: <11523@csli.Stanford.EDU> Date: 23 Dec 89 01:41:54 GMT References: <984@ux.acss.umn.edu> <11467@csli.Stanford.EDU> <636@chem.ucsd.EDU> Sender: poser@csli.Stanford.EDU (Bill Poser) Reply-To: poser@csli.stanford.edu (Bill Poser) Organization: Center for the Study of Language and Information, Stanford U. Lines: 44 tps@chem.ucsd.edu (Tom Stockfisch) suggests the following in place of my regexp based solution: int /* really BOOL */ isInteger(string) char *string; { char *endptr; (void)strtol( string, &endptr, 10 ); return endptr != string; } and goes on to suggest that the regexp solution involves unnecessary software. One reason not to use this version is because it doesn't work. Since strtol sets endptr to point to the character that terminated the scan, it returns true if a non-null prefix of the string is an integer, which is not the same thing as testing whether the string as a whole is an integer. To use strtol to do this correctly you have to check whether endptr is the same as the end of the string. Now, if you aren't loading the regexp stuff for any other purpose, you can keep your code size down a bit by avoiding the use of regexp. But if you're using regexp anyhow (your interactive program does have apropos, doesn't it?) it doesn't cost much to use it here. The other reason to use the regexp approach is that it makes it quite simple to implement other predicates. Want to see if the string is a positive integer? Just get rid of the - in the regular expression. Want to see if you've got a floating point number in non-exponential notation? Want to see if you've got a specified number of digits? These are all easy to do using regular expressions, but harder to do otherwise. Regular expression techniques provide very general and flexible solutions to problems of this class. If you really have a situation in which the overhead is a problem, by all means use more specialized techniques with lower overhead, but just as it is foolish to engage in speed optimizations that have little real impact on performance, so it is foolish to avoid simple general techniques when it isn't clear that the overhead is significant. Bill