cfunctiondeclaration

Function declaration order matters in c language or am I doing something wrong?


I get this error:

arthur@arthur-VirtualBox:~/Desktop$ gcc -o hw -ansi hw1.c
hw1.c: In function `main':
hw1.c:27:16: warning: assignment makes pointer from integer without a cast [enabled by default]
hw1.c: At top level:
hw1.c:69:7: error: conflicting types for `randomStr'
hw1.c:27:18: note: previous implicit declaration of `randomStr' was here

While compiling this code:

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

int main(int argc, char** argv)
{
        char *rndStr;
        rndStr = randomStr(FILE_SIZE);
        /* Do stuff */
        return 0;
}

/*Generate a random string*/
char* randomStr(int length)
{
        char *result;
        /*Do stuff*/
        return result;
}

If I switch the function order around it works Why?


Solution

  • Except in a few exceptions, an identifier in C cannot be used before it has been declared.

    Here is how to declare a function outside its definition:

    // Declare randomStr function
    char *randomStr(int length);