Check for double characters - Functions

Viewed 41

I have created a bit of code, that can check an input text for double characters. I got to work if I had all my code inside my main function, but have some trouble when I want to create an extra function. The error I am getting is the following: "error: control may reach end of non-void function", which I have identified to that the system cannot identify a return value from my count_double_characters function.

Can you help me understand what I am doing wrong?

#include <stdio.h>
#include <string.h>

int count_double_characters(char *ch);

int main(void)

{
char input[400];
printf("Write the text you want to check: ");
fgets(input, sizeof(input), stdin);
count_double_characters(input);
}   


int count_double_characters(char *ch)
{
char n = strlen(ch);  
int count_double = 0;

for (int i = 0; i < n; i++)
{
    for (int j = i + 1; j < n; j++)
    {
        if (ch[i] == ch[j])
        {
            count_double++;
        }
    }

}

if (count_double > 0)
    {
        char s = printf("Its a double!\n");
        return s;
    }
    
else if (count_double == 0)
    {
        char d = printf("Looks good\n");
        return d;
    }
}
1 Answers

Consider this section of your code:

if (count_double > 0)
    {
        char s = printf("Its a double!\n");
        return s;
    }
    
else if (count_double == 0)
    {
        char d = printf("Looks good\n");
        return d;
    }

  // if count_double is less than 0, the program goes here
  // but there is non return statement, meaning that the function
  // does not return any value.
  // That what's the error message is telling you
}

Now you will tell me that count_double can never be 0, which is correct, but apparently the compiler is not smart enough to detect this.

To correct, you can simply drop the if (count_double == 0) or replace it with if (count_double <= 0).

Related