Gary
Gary

Reputation: 318

Loop with 2 conditions is exiting when 1 condition is met

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

Answers (3)

Jens
Jens

Reputation: 72619

This loop runs as long as

  1. buf and match differ somewhere in the first 3 characters, AND
  2. check(buf[3]) is nonzero

Is that what you want? In other words, the loop exits when either

  1. buf and match share the same three initial characters OR
  2. check(buf[3]) is zero

I 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

Sudip Das
Sudip Das

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

Hatted Rooster
Hatted Rooster

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

Related Questions