I'm just learning C++ and I have a little code here:
using namespace std;
int main()
{
cout<<"This program will calculate the weight of any mass on the moon\n";
double moon_g();
}
double moon_g (double a, double b)
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
It compiles, but when I run it it only prints out:
This program will calculate the weight of any mass on the moon
but doesn't execute the moon_g
function.
This line:
doesn't actually do anything, it just states that a function
double moon_g()
exists. What you want is something like this:This won't work yet, because you don't have a function
double moon_g()
, what you have is a functiondouble moon_g(double a, double b)
. But those arguments aren't really used for anything (well, they are, but there's no reason to have them passed in as arguments). So eliminate them from your function like so:(And declare the function before you call it.) More refinements are possible, but that'll be enough for now.
This is a function declaration:
this won't call a function, and if you did have it correct, which means adding two parameters since that is how you define it below:
it would not work because you either need to move the definition of
moon_g
beforemain
or add a forward declaration beforemain
like this:Although it seems like
a
andb
are not inputs but values you want to return back tomain
then you would need to use references and it would need to be declared and defined like this:A useful thread to read especially if you are starting out would be What is the difference between a definition and a declaration?.
Which compiler you use makes a difference here
clang
provides the following warning:while I can not get
gcc
norVisual Studio
to warn me about this. It is useful in the long run to try code in different C++ compilers when you can, it can be a very educational experience and you don't have to install them either since there are plenty of online C++ compilers available online.There is huge difference between calling a function and declaring it just as there is difference between local variables and function arguments.
I suggest reading basic tutorials first.
Anyway, thats how code should look like:
There are two problems in your code.
Firstly, if you want to call your function
you should provide the two parameters
a
andb
. Buta
andb
are calculated in the body of function definition, it is unnecessary to declare the two parameters. You can write like this.Then, in the main function, your calling function statement is wrong. You may want to receive the return value. So, you should write the code like this.
Finally, it is mostly recommended that the function which will be called by another function should be declared or defined previously.