Home > database >  Strlen() Vs Strcmp for checking empty char array variable
Strlen() Vs Strcmp for checking empty char array variable

Time:11-16

#include <iostream>
#include <cstring>

int main()
{
    char c1[5];
    char c2[5];

    if ( strlen(c1) == 0)
    {
        std::cout<<" c1 empty";
    }

    if (strcmp(c2, "") == 0)
    {
        std::cout<<" c2 empty";
    }

    return 0;
}

if ( strlen(c1) == 0)

lea     rax, [rbp-5]
movzx   eax, BYTE PTR [rax]
test    al, al
jne     .L2

if (strcmp(c2, "") == 0)

movzx   eax, BYTE PTR [rbp-10]
movzx   eax, al
test    eax, eax
jne     .L3

Not able to differentiate assembly code, they almost generate same code in assembly. Which is efficient way of checking array as empty? Any help or more information will be appreciated.

CodePudding user response:

C has something called the as-if rule. Your code has to behave as if strlen was called and the result compared to 0. But that does not mean it has to do exactly that.

A common optimization is to inline the call to strlen, since it's simple. This is legal, because your C can't notice the inlining. Your code behaves as if strlen was called.

Another common optimization is to eliminate parts of the code that do not matter. E.g. here it doesn't matter whether strlen would return 1, 2 or any other non-zero value.

CodePudding user response:

strlen()

strlen() fucntion return number of characters in that string . Starts counting from first character till null character \0 encountered .

strcmp()

strcmp() function can return 3 different integer variables --->
a.) Return 0 if both string are identical.
b.) Return integer value greater than 0 if ASCII value of the first not matching character of left string is greater than that of corresponding character of right string .
c.) Return integer value less than 0 if ASCII value of first not matching character of left string is less than ASCII value of corresponding character of right string.

Check out this code to see difference --->

#include<iostream>
#include<cstring>
int main()
{
char c1[5],c2[5];
std::cin>>c1>>c2;
std::cout<<"Length of first string ="<<strlen(c1)<<"\n";
std::cout<<"Value returned by strcmp() ="<<strcmp(c1,c2);
return 0;
} 
  • Related