2016-07-08 78 views
2

我有以下代码:如果while循环使用C

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; 
} 

我想这样做是:一次在if结构的代码被执行(即,在如果条件评估为真),我不想在所有以下的while循环中执行它,我怎么能这样做呢?

+1

请更具体的你想要什么 –

+4

不要投给'为const char *'/ clear-,这是无用的,毫无意义的。也不要将文字转换为'unsigned int',如果你想要一个'unsigned int'文字,可以使用** 16777221U **。 –

+0

@GiorgiMoniava在所有的while循环中,如果在某个特定的循环中if条件被评估为true,那么在所有的循环中,我想忽略这个如果结构,这就是我想要的 –

回答

4
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; 
} 
+0

this肯定会比我的代码使用更少的时间。 –

1

我能想到的这样做的方法有两种:

  1. 较短的核心,效率较低 - >使用标志:

    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. 较长的代码,但多一点高效 - >拆分代码:

    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(); 
    } 
    

第二种方法更高效,因为通用代码具有更好的现金局部性,并且您不必为每次迭代都执行if语句,但显然情况并非如此。根据的代码是如何执行的次数,它可能是值得的......

+0

如果'foo()'没有被内联,第二个代码可能效率更低 –

+0

每种方法都有其优点,但我更喜欢第一种方法。 –

+0

'flag'完全可以从第二个片段中删除。 – alk