Question:
I have a question about functions in c++, I have learned how to make functions using prototypes as in the following code:
#include<iostream>
using namespace std;
int suma(int, int);
int main(){
int a = 5, b = 4;
cout<<"\nLa suma de los numeros "<<a<<" y "<<b<<" es: "<<suma(a,b)<<endl;
return 0;
}
int suma(int x, int y){
int resultado;
resultado = x + y;
return resultado;
}
But I don't know what is the difference with the following where I don't use the prototype of the "sum" function:
#include<iostream>
using namespace std;
int suma(int x, int y){
int resultado;
resultado = x + y;
return resultado;
}
int main(){
int a = 5, b = 4;
cout<<"\nLa suma de los numeros "<<a<<" y "<<b<<" es: "<<suma(a,b)<<endl;
return 0;
}
I have seen that several people use the functions in c++ without defining the prototype, I am not very clear if there is any difference between these two forms, since both work for me. I have also read that prototypes are required in c++, but the prototype is not used in the second code. So what is the difference between using or not using prototypes in c++ and if they work the same in c?
Answer:
The only difference is in non-member-functions, that is, in functions that do not belong to a class.
In these non-member-functions, the compiler has to know the prototype before the first call :
int suma( int x, int y ){ return x + y; }
int main( ) {
std::cout << "Suma: " << suma( 1, 2 ) << std::endl;
return 0;
}
Ok, it works correctly. The compiler knows what suma( )
is and what arguments it expects before you use it in main( )
. But nevertheless:
int main( ) {
std::cout << "Suma: " << suma( 1, 2 ) << std::endl;
return 0;
}
int suma( int x, int y ){ return x + y; }
error: 'sum' was not declared in this scope
In this case, the compiler doesn't know what suma
and protest is. Here, it is mandatory to use the prototype:
int suma( int x, int y );
int main( ) {
std::cout << "Suma: " << suma( 1, 2 ) << std::endl;
return 0;
}
int suma( int x, int y ){ return x + y; }