Sijith
Sijith

Reputation: 3932

Optimized code for two string compare in if condition

I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition

if (strcmp(Buff1(), Config1) == 0)
{ 
    if (strcmp(Buff2, Config2) == 0)
    {
      // my code goes here
    }
}

Upvotes: 0

Views: 134

Answers (3)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.

Upvotes: 0

Mai Benami
Mai Benami

Reputation: 76

In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true. So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.

Upvotes: 0

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

The equivalent code is:

if ((strcmp(Buff1(), Config1) == 0)) &&
    (strcmp(Buff2, Config2) == 0))
{
    // my code goes here
}

Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.

You do get a difference when you add else clauses:

if (strcmp(Buff1(), Config1) == 0)
{ 
    if (strcmp(Buff2, Config2) == 0)
    {
      // my code goes here
    }
    else 
    {
        // else 1
    }
}
else 
{
    // else 2
}

Compared to:

if ((strcmp(Buff1(), Config1) == 0)) &&
    (strcmp(Buff2, Config2) == 0))
{
    // my code goes here
}
else 
{
    // Single else clause
}

Upvotes: 1

Related Questions