Calling a function in main

前端 未结 4 569
暖寄归人
暖寄归人 2020-11-28 16:52

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         


        
4条回答
  •  忘掉有多难
    2020-11-28 17:18

    This is a function declaration:

    double moon_g();
    

    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:

    moon_g( a, b ) ;
    

    it would not work because you either need to move the definition of moon_g before main or add a forward declaration before main like this:

    double moon_g (double a, double b) ;
    

    Although it seems like a and b are not inputs but values you want to return back to main then you would need to use references and it would need to be declared and defined like this:

    double moon_g (double &a, double &b) ;
                          ^          ^
    

    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:

    warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
        double moon_g();
                     ^~
    

    while I can not get gcc nor Visual 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.

提交回复
热议问题