Search code examples
csyntaxgcc-warningfunction-declaration

Warning: type of ‘numRest’ defaults to ‘int’ (in function 'sleep')


I get a warning In function ‘sleep’: warning: type of ‘numRest’ defaults to ‘int’ and I have no idea why. It runs perfectly fine but apparently I got this warning. Does anyone else get this warning when they run it?

void sleep(numRest){

if ((numRest >= 0) && (numRest <=4)){
    printf("Sleep deprived!");
}


else if ((numRest > 4) && (numRest < 6)){
    printf("You need more sleep.");
}


else if ((numRest >= 6) && (numRest < 8)){
    printf("Not quite enough.");
}


else{
    printf("Well done!");
}

return;
}

int main()
{
int numSleep = -1;


if (numSleep == -1){
    printf("Test 1\n");
    printf("Input: -1\n");
    printf("Expected Result: Error, you cannot have a negative number of hours of sleep.\n");
    printf("Actual Result: ");
    sleep(numSleep);
    printf("\n\n");

    numSleep = 4.5;
    printf("Test 2\n");
    printf("Input: 4.5\n");
    printf("Expected Result: You need more sleep.\n");
    printf("Actual Result: ");
    sleep(numSleep);
    printf("\n\n");


}





return 0;
}

Solution

  • The issue is with the function signature definition.

     void sleep(numRest) {
    

    should be

    void sleep(int numRest) {
    

    Otherwise, the compiler will "assume" (now obsolete by latest standard) that the missing datatype is int.

    Related, quoting from C11, Major changes (over previous versions) list

    • remove implicit int

    That said,

    • sleep() is a library function already, prototyped in unistd.h, do not try to use the same for for user-defined functions.
    • int main() should be int main(void), at least for hosted environments to conform to the standard.