Search code examples
cstringfor-loopsubstring

Multiple conditions in 'for' loop in C


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.


Solution

  • 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.