Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 668
Rüppell's Vulture Avatar asked Apr 02 '13 04:04

Rüppell's Vulture


People also ask

Why is function declaration important?

Function declarations are important because a calling convention (part of the ABI of a platform) can define different places for arguments and return values based on the types a function returns and accepts as arguments.

What is implicit declaration of function warning?

implicit declaration of function means that you are trying to use a function that has not been declared. In our example above, StartBenchmark is the function that is implicitly declared.

Does the main function need to be declared?

You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files. But you can't call main in C++ so you don't need one.

How do you declare a function explicitly?

You can declare a function as an explicitly defaulted function only if the function is a special member function and has no default arguments. For example: class B { public: int func() = default; // Error, func is not a special member function.


1 Answers

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.

like image 183
Alexey Frunze Avatar answered Sep 26 '22 15:09

Alexey Frunze