home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!stanford.edu!leland.Stanford.EDU!dkeisen
- From: dkeisen@leland.Stanford.EDU (Dave Eisen)
- Subject: Re: Multiple &'s in an if statement
- Message-ID: <1992Nov23.180904.9445@leland.Stanford.EDU>
- Keywords: &
- Sender: news@leland.Stanford.EDU (Mr News)
- Organization: Sequoia Peripherals, Inc.
- References: <1992Nov23.164530.19214@iacd>
- Distribution: comp.lang.c
- Date: Mon, 23 Nov 92 18:09:04 GMT
- Lines: 64
-
- In article <1992Nov23.164530.19214@iacd> bcochell@ips.iacd.honeywell.com writes:
- >Greetings,
- >
- >Can anyone explain why this works correctly (That is, it checks to see that
- >the last 5 characters of name are all digits and that it is null terminated):
- >
- > if ( isdigit(name[strlen(path)]) &
- > isdigit(name[(strlen(path) + 1)]) &
- > isdigit(name[(strlen(path) + 2)]) &
- > isdigit(name[(strlen(path) + 3)]) &
- > isdigit(name[(strlen(path) + 4)]) )
- > if ( iscntrl(name[(strlen(path) + 5)]) ) {
- > printf("%s\n",name);
- > }
- >
- >While the following does not?:
- >
- > if ( isdigit(name[strlen(path)]) &
- > isdigit(name[(strlen(path) + 1)]) &
- > isdigit(name[(strlen(path) + 2)]) &
- > isdigit(name[(strlen(path) + 3)]) &
- > isdigit(name[(strlen(path) + 4)]) &
- > (name[(strlen(path) + 5)] == NULL ) ) {
- > printf("%s\n",name);
- > }
-
- Because you are using '&' (bitwise and), not '&&' (boolean and) and
- isdigit has some value other than 0 or 1. The functions declared
- in <ctype.h>, isdigit, islower, etc. are guaranteed to return some
- non-zero value if the character in question staisfies the condition;
- they are *not* guaranteed to return 1.
-
- So suppose isdigit returns 4 if the character being tested is a
- digit. And suppose that name[strlen (path) + 5] works and returns
- 1. (It need not work because NULL can be defined as (void *) 0. Even
- if it works it is bad programming practice to use NULL in this
- context where it is not a pointer).
-
- Then the method that does not work comes down to evaluating
-
- 4 & 4 & 4 & 4 & 4 & 1
-
- which indeed is equal to 0 because 1 and 4 have no nonzero bits
- in common.
-
- Change your example to:
-
- if ( isdigit(name[strlen(path)]) &&
- isdigit(name[(strlen(path) + 1)]) &&
- isdigit(name[(strlen(path) + 2)]) &&
- isdigit(name[(strlen(path) + 3)]) &&
- isdigit(name[(strlen(path) + 4)]) &&
- (name[(strlen(path) + 5)] == '\0' ) ) {
- printf("%s\n",name);
- }
-
- or even better, something that doesn't recompute strlen (path) 6 times.
-
-
- --
- Dave Eisen Sequoia Peripherals: (415) 967-5644
- dkeisen@leland.Stanford.EDU Home: (415) 321-5154
- There's something in my library to offend everybody.
- --- Washington Coalition Against Censorship
-