Reputation: 318
I want the loop to exit when both strncmp() and check() return 0, meaning they both found a match. The problem is, when check() returns 0 and strncmp() does not return 0 the loop is exiting.
while (strncmp(buf, match, 3) != 0 && check(buf[3]) != 0)
{
}
I have checked the values in buf and match and they do not match when it exits. buf[3] does match when it exits.
Upvotes: 1
Views: 138
Reputation: 72619
This loop runs as long as
buf
and match
differ somewhere in the first 3 characters, ANDcheck(buf[3])
is nonzeroIs that what you want? In other words, the loop exits when either
buf
and match
share the same three initial characters ORcheck(buf[3])
is zeroI want the loop to exit when both strncmp() and check() return 0
Then you can rewrite the loop to be very easy to verify against your requirement:
for(;;) {
...
if (strncmp(buf, match, 3) == 0 && check(buf[3]) == 0)
break;
...
}
Now place the negated condition in the controlling expression of the loop:
while (! (strncmp(buf, match, 3) == 0 && check(buf[3]) == 0) ) {
...
}
If you are somewhat into computer science, you realize that not(A and B)
is--per de Morgan's Laws--equivalent to (not A) or (not B)
. This finally yields:
while (strncmp(buf, match, 3) != 0 || check(buf[3]) != 0) {
}
So your error was using &&
instead of ||
for the logical operator.
Upvotes: 3
Reputation: 1208
u can try this ...
int c,d;
while ((c=strncmp(buf, match, 3) != 0) && (d=check(buf[3]) != 0))
{}
Description:
strncmp() will return a value that have to store in a var..if u don't do then how it will compare with 0..same as also check().
Upvotes: 2
Reputation: 36463
You are using &&
so you're saying both strncmp(buf, match, 3)
and check(buf[3]) != 0
must be met in order for the loop to continue. To get the result you specified you should use ||
Upvotes: 8