-3
#include<iostream>
using namespace std;

int sum(int ,int);
int sum(int ,int );
int main(){
    cout<<sum(1,3)<<endl;
}
int sum(int a,int b){
    cout<<"hi "<<endl;
    return a+b;
}
int sum(int a,int b,char c){
    return a+b+c;
}

In the above program, I have defined a function after main without prototype declaration but the compiler did not generate error message.

Biffen
  • 6,249
  • 6
  • 28
  • 36

1 Answers1

5

Prototypes are not strictly necessary. Functions must be declared before they are used, and defined (somewhere) if they are used.

Separate declarations allows header files to announce the existence of a function, while another file actually defines it (.c, .cpp, or even a library).

However, if you simply implement a function without a prototype, then the definition is also its own declaration. If it shares the same name as another existing function with a different signature, it simply adds to the overload set (from that point onward) for that name.

Finally, it is not an error to define a function that isn't called. Think about how many functions are declared when you include <iostream> that you haven't called! Unused functions will not appear in the final resulting artifact being produced.

Problems that can arise occur when you provide multiple definitions for the same function (linker error), or different translation units provide different definitions of inline functions (One Definition Rule (ODR) violation).

Chris Uzdavinis
  • 6,022
  • 9
  • 16
  • What do you mean with "prototypes are not strictly necessary"? – Peter - Reinstate Monica Jun 18 '21 at 12:27
  • @Peter-ReinstateMonica s/strictly/always ? I took "strictly" to mean "always", as it can do. – Bathsheba Jun 18 '21 at 12:28
  • 1
    @Peter-ReinstateMonica By that, I meant you can define a function even if it's not previously declared. Headers with inline functions do this all the time. I.e. it is _not_ required to `void f(); void f() { }`, with the first being an explicit prototype, and the second being a definition. You can simply `void f() { }` and it is its own declaration. If other files want to call it and the function definition isn't immediately visible, then a prototype will be enough info to satisfy the compiler, and the linker will find/resolve the function's symbol later. – Chris Uzdavinis Jun 18 '21 at 12:34