Bohao LI
Bohao LI

Reputation: 2713

if in while loop in C

I have the following code:

while(tmp->next != NULL)
{
    if(tmp->code == (unsigned int)16777221)
    {
        CU_ASSERT_STRING_EQUAL("3GPP Zh", tmp->name);
    }
    if(strcmp((const char*)tmp->name, (const char*)"IUT-T Rs") == 0)
    {
        CU_ASSERT_EQUAL((unsigned int)16777235, tmp->code);
    }
    tmp = tmp->next;
}

What I want to do is this: once the code in the if structure is executed (that is to say, the if condition is evaluated to true), I don't want to execute it anymore in all the following while loops, how could I do this?

Upvotes: 2

Views: 130

Answers (2)

Pandrei
Pandrei

Reputation: 4951

I can think of two ways of doing this:

  1. shorter core, less efficient -> use a flag:

    int flag = 0;
    while(tmp->next != NULL)
    {
        if(flag && tmp->code == (unsigned int)16777221)
        {
            flag = 0;
            CU_ASSERT_STRING_EQUAL("3GPP Zh", tmp->name);
        }
        // some other code
        tmp = tmp->next;
    }
    
  2. longer code, but a little more efficient ->split the code:

    void foo()
    {
      //code that needs to be executed
    }
    
    while(tmp->next != NULL)
    {
        if(tmp->code == (unsigned int)16777221)
        {
            CU_ASSERT_STRING_EQUAL("3GPP Zh", tmp->name);
            break;
        }
        foo();
     }
     while(tmp->next != NULL)
     {
        foo();
     }
    

The second way is more efficient because the common code has better cash locality and you don't have to execute the if statement for every iteration, when it's obvious the condition will not be true. Depending of how often the code is executed, it may be worth it...

Upvotes: 1

Sergio
Sergio

Reputation: 8209

int once = 0;

while(tmp->next != NULL)
{
    if(!once && tmp->code == (unsigned int)16777221)
    {
        once = 1;
        CU_ASSERT_STRING_EQUAL("3GPP Zh", tmp->name);
    }
    /* deal with subsequent if's in the same manner */
    tmp = tmp->next;
}

Upvotes: 4

Related Questions