Search code examples
cequalityc-stringsreturn-typefunction-definition

getting no output (expecting boolean output)


So I tried not using the string.h file. I created string length function which works. I then created a function to check if two functions are same or not but I am getting no output. I have tested the string length function and that works. I am not sure what I am doing wrong in the second function. Please point out the error.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

char stringLength(char userString[])
{
    int i=0,count=0;
    while (userString[i] != '\0')
    {
        count = (count + 1);
        i = (i + 1);
    }
    return count;

}


bool stringCheck (char a[], char b[])
{
    bool isEquals = false;
    if (stringLength(a) == stringLength(b))
    {
        int i=0, count=0;
        while (i<stringLength(a))
        {
            if (a[i] == b[i])
            {
                count+=1;
            }

            i+=1;
        }

        if (count == stringLength(a))
            isEquals = true;
        else
            isEquals = false;
    }
    else
        isEquals = false;

    return isEquals;
}

int main()
{
    stringCheck("abcd", "abcd");
    return 0;
}

Solution

  • The function works.

    Its just that you are not catching the return value of stringCheck() function. You can do that as shown below.

    bool strMatch = stringCheck("abcd", "abcd");
    if(true == strMatch)
    {
        // Do something when the strings are same
    }
    else
    {
        // Do something else otherwise
    }
    

    Also, as an improvement - In stringCheck() function, you have a loop

    while (i < stringLength(a))
    

    There is nothing wrong with it, but you can improve the efficiency of your code by saving the length of the string into a variable and use that variable for polling in the while loop. In stringCheck function:

    int i=0, count=0;
    char strLength = stringLength(a);
    while (i < strLength)
    

    This will work because the length of strings aren't changing within the loop.

    I find issues with stringLength() function. First is, the data type used for variable returning the length count is int whereas the return type set for function is char. Also, consider changing the return type of the function stringLength() to size_t along with the data type for variable count in the same function.

    char stringLength(char userString[])
    

    to

    size_t stringLength(char userString[])
    

    With a return type as char, your function will misbehave if the length of the string is more than 127 bytes.

    The next improvement in the stringLength() function is, i and count seems to be updated at the same time. I can't think why you need two variables there when you can simply return i in place of count.

    Your compiler would have warned you about all these points if you had compiled your code with certain gcc flags such as -Wall to start with.