3

Why does my code work ? I am calling the function generateNumber before declaring it, and I haven't set a prototype at the beginning of the file, so normally it shouldn't work, should it ?

Here is my code :

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


int main(int argc, const char * argv[]) {
    int max = 100;
    int min = 1;
    int mysteryNumber = generateNumber(min, max);
    int enteredNumber = min-1;
    do{
        printf("Enter a number !\n");
        scanf("%d", &enteredNumber);
        if (enteredNumber > mysteryNumber) {
            printf("It's less !");
        }else if(enteredNumber < mysteryNumber){
            printf("It's more !");
        }
    }while (enteredNumber != mysteryNumber);
    printf("Congratulations, the mystery number was %d \n", mysteryNumber);
    return 0;
}

int generateNumber(int min, int max){
    srand(time(NULL));
    return (rand() % (max - min + 1)) + min;
}

Thanks by advance !

Quentouf
  • 103
  • 7

2 Answers2

5

Surprisingly, this is one of the rare cases when it actually should work with old compilers - specifically, with compilers prior to C99. Still, you shouldn't do it: implicit int has been removed in C99, because it makes code fragile.

When a function lacks prototype, older C compilers used to assume that all its arguments match the types of expressions that you pass, and that their return type is int. Your function happens to match this description: you pass two integers, and treat the return value as an int.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You are right it shouldn't work. My gcc (6.1.0) produces:

test.c: In function ‘main’:
test.c:9:25: warning: implicit declaration of function ‘generateNumber’ [-Wimplicit-function-declaration]
     int mysteryNumber = generateNumber(min, max);
                         ^~~~~~~~~~~~~~

It "works" because most compilers are permissive of this by providing an implicit function declaration. However, it's not valid in modern C.

Before C99 removed this implicit function declaration from the standard, it was allowed. But it's not valid anymore since C99. If your compiler doesn't provide warnings for this, try to increase the warning levels.

melpomene
  • 84,125
  • 8
  • 85
  • 148
P.P
  • 117,907
  • 20
  • 175
  • 238
  • http://stackoverflow.com/questions/8440816/warning-implicit-declaration-of-function Note that this is a warning only, so it will still compile. – sabbahillel Jan 12 '17 at 19:47
  • 1
    @sabbahillel C standard doesn't distinguish between warnings and errors -- only diagnostics. So, compiling with (or even without in some cases e.g. undefined behaviours) warnings isn't necessarily mean it's *valid* (per C standard). – P.P Jan 12 '17 at 19:49