Reputation: 3
I am learning C++. I am following along with a learning tutorial. After creating (forgive me if I am not labeling this correctly) a function that calculates exponentials with the for() loop. We are learning how to use a void function to call it. In all of the code there are few times the parameters (hopefully labeling correctly) do not include the return type. It is creating an itch for me as I really am taking things slow trying to understand everything so far.
#include <iostream>
double power_function(double base, double exponent)
{double solution = 1;
for(double i = 0; i < exponent; i++)
{solution = solution * base;
}
return solution;
}
void print_power(double base, double exponent)
{ double void_operation = power_function(base,exponent);
/* Why do we call without the return type? Cause it is already defined? */
std::cout << "The base of " << base << " with an exponent \n.";
std::cout << " of " << exponent << " is equal to " << void_operation;
}
int main ()
{int base test, exponent test;
std::cout << "What is the base,\n.";
std::cin >> base_test;
std::cout << "What is the exponent?\n.";
std::cin >> exponent_test;
printpower(base_test, exponent_test);
}
Upvotes: 0
Views: 61
Reputation: 66922
First, a function should be declared:
double power_function(double base, double exponent)
This tells the compiler that a function exists named power_function
, which takes two double
parameters, and returns a double. (The definition might immediately follow, or the definition might be elsewhere, but that's not relevant int his case) From then, on, the compiler knows the parameter types, and the return type.
So when the compiler sees:
double void_operation = power_function(base,exponent);
The compiler will generate code to copy both those parameters as doubles to the stack (converting them to double
if needed), and then call the function. When the function returns, the compiler already knows the return type is a double
, so it will take the top item on the stack as a double
and will assign it to void_operation
(again, converting from double
if needed).
Upvotes: 0
Reputation: 96
When you call functions in C++ you don't need to specify the return type because it's already specified in the function definition above.
Here's a really simple example of this from cplusplus.com
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
addition()
has return type int but when its called
z = addition (5,3);
the return type is not specified.
Upvotes: 1