Search code examples
ccs50caesar-cipher

C compiling Error: non-void function does not return a value in all control paths - CS50


I'm doing the CS50 course in C and am working on the problem set from week 2. I'm an absolute beginner so there's probably a lot wrong with my code. For now, I'm trying to create a function that checks if the user has correctly used the command line input and if that input consists of only integers.

this is my code:

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

bool only_digits(string s);

int main(int argc, string argv[])
{
    if (argc == 2 & only_digits > 0)
    {
        printf("test\n");
    }
    else
    {
        printf("usage: ./caesar key\n");
    }
}

bool only_digits(string s)
{
    for (int i = 0, n = strlen(s); i < n; i++)
        {
            if (isdigit(i))
            {
                return 0;
            }

            else
            {
                return 1;
            }
        }
}

This is the error:

caesar/ $ make caesar 
caesar.c:34:1: error: non-void function does not return a value in all control paths [-Werror,-Wreturn-type]
}
^
1 error generated.

Thanks in advance, and excuse me for the many mistakes there probably are in the code. make: *** [: caesar] Error 1


Solution

  • The logic of your function doesn't match its name. Presumably, you want only_digits to check if the passed in string is comprised entirely of digits. However, you return 0 (false) when you find a digit, that makes no sense. You're also not calling the function correctly:

    #include <cs50.h>
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    int main(int argc, string argv[])
    {
        // use && for logical AND, & is bitwise AND
        // Pass argv[1] to only_digits
        if ((argc == 2) && only_digits(argv[1]) == true)
        {
            
            printf("test\n");
        }
        else
        {
            printf("usage: ./caesar key\n");
        }
    }
    
    bool only_digits(string s)
    {
        // strlen returns a size_t type, use that
        size_t n = strlen(s);
        for (size_t i = 0; i < n; i++)
        {
            // check each digit. If it's _not_ a digit, then we're
            // done, no point in checking the rest of the string
            if (!isdigit(s[i]))
            {
                return false;
            }
        }
    
        // we've looped thru the entire string. If we make it here
        // and haven't returned false, then we know every char in
        // the string is a digit, return true
        return true;
    }
    

    Demo