In my code, why is lack of a function declaration a non-issue for one function, but throws a warning for another?

In the following program,I use two functions prd() and display().I have declared neither of them ahead of main() before invoking them in main(),and I have defined both after main().Yet while prd() works smoothly inside main(),invoking display() shows the warning " previous implicit declaration of 'display' was here ".What is different about display() that there is a warning for it but not for the other funciton prd()?I have declared neither of them to begin with.Still there is warning due to invocation of one, but other one works fine.

    #include<stdio.h>

    int main()
    {
        int x=8,y=11;

        printf("The product of %d & %d is %d",x,y,prd(x,y));

        display();

        return 0;
    }

    int prd(int x,int y)
    {
        return x*y;
    }

    void display()
    {
        printf("\n Good Morning");
    }

PS: And I would really appreciate if you can answer this secondary question --"Is function declaration not necessary at all in C provided there is a definition for it?".I have the habit of declaring all functions of the program before the main() function, and then defining them after the main() function.Am I wrong?

Upvotes: 6

Views: 144

Answers (3)

hjpotter92
hjpotter92

Reputation: 80639

The error occurs because C considers all non-initiated functions with a return type of int. Your display function is later defined with void return type.

Changing the return type of display() to int removes the warning.

Upvotes: 4

Rohan
Rohan

Reputation: 53326

By default, compiler assumes non-declared functions as returning int.

This is true for your prd function, but it does not match with display() as its void. This causes compiler to raise a warning.

For 2nd, its always appropriate to declare functions.

Upvotes: 2

Alexey Frunze
Alexey Frunze

Reputation: 62058

When you use undeclared display() the compiler implicitly declares it as if it were returning int.

When the compiler finally sees the definition of display(), it sees that the return type is void, but it's already assumed it be int and so the definition and the implicit declaration differ, hence the error/warning.

Upvotes: 9

Related Questions