1

I am trying to find a substring in a string. While doing this, I understood that to check for multiple conditions in a for loop if we write

for(i=0; condition1, condition2; i++)

the value of condition1 is found and then discarded. Then, the value of condition2 is found and returned. To get around this, we need to use && in case of multiple conditions to be checked by a for loop in here.

for(i=0; condition1 && condition2; i++)

So far I believe I understood right, but the following for loop is not working.

for(i=0; (a[i] != '\0') && (a[i] == b[0]); i++)
{
    j = i + 1;
    k = 1;
    while(a[j] == b[k] && a[j] != '\0' && b[k] != '\0')
    {
        j++;
        k++;
    }
    if(b[k] == '\0')
    {
        return i;
    }
}
return -1;

When I wrote the above for loop, the control is entering the loop and performing the operations, whereas in the following code, control is not even entering the for loop, and it is working correctly.

for(i=0; a[i] != '\0'; i++)
{
  if(a[i] == b[0])
  {
      j = i + 1;
      k = 1;
      while(a[j] == b[k] && a[j] != '\0' && b[k] != '\0')
      {
          j++;
          k++;
      }
      if(b[k] == '\0')
      {
          return i;
      }
  }
}

Is there something I am missing about internal processing in for loops? I believe the way they both should work is the same.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yash
  • 1,357
  • 2
  • 23
  • 34
  • A canonical question is *[Multiple conditions in a C 'for' loop](https://stackoverflow.com/questions/16859029/)*. But there must be one from 2008 or 2009. – Peter Mortensen Sep 01 '22 at 22:55

2 Answers2

0

These blocks of code don't do the same thing. In the first one, if either condition isn't met then the for loop will stop iterating. In the second block, if the first condition isn't met, then the for loop will stop iterating, whereas if the second one isn't met the internal code isn't executed, but the for loop will continue.

As for the && operator.... It will evaluate all of the conditions in order and it will stop and evaluate to false as soon as it hits an individual component that evaluates to false. If it doesn't run into any false condition then it will evaluate to true.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PandaRaid
  • 618
  • 1
  • 9
  • 22
0

In the first code snippet your for loop has two conditions. Remember when one of them is not true, the loop will terminate immediately.

In the second code snippet, you just have one condition in the for loop. The second condition is inside an if case. So if condition2 is wrong the if case won't be executed, but the for loop will still continue.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RomCoo
  • 1,868
  • 2
  • 23
  • 36