LiuHao
LiuHao

Reputation: 562

Why can't I initialize parameters when calling functions in C++?

Below is my program. In the main function , I initialized a and b when calling the add2var function. Does C++ allow initialization in the parentheses when calling functions?

#include "stdafx.h"
#include <iostream>

using std::cout;
using std::cin;
using std::endl;
int add2var(const int a, const int b);


int main()
{
    int c = add2var(int a = 5, int b = 6.1);
    cout << c << endl;
    return 0;
}

int add2var(const int a, const int b)
{
    return a + b;
}

It produce errors as follows.

syntax error : 'int' should be preceded by ')'

function does not take 0 arguments

syntax error : ')'

Upvotes: 0

Views: 6240

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

C++ does not directly support names parameters a.k.a. (Python) keyword arguments.


Possibly you just want the ability to specify argument values, nothing more. I suspect that, because you're attempting to store a floating point value 6.7 in an int, which indicates that you're very new to programming. If that's all you want to, namely specify argument values, then you can use ordinary positional arguments, like this:

#include <iostream>
using namespace std;

auto add2var( int const a, int const b )
    -> int
{ return a + b; }

auto main() -> int
{
    int const c = add2var( 5, 6 );
    cout << c << endl;
}

Note that there's no stdafx.h here.

In a Visual Studio project turn off precompiled header support in the project settings in order to make compile without stdafx.h, compile.


If you really want to have named arguments For simple cases like the one presented you can use the named parameters idiom a.k.a. NMI. Essentially NMI consists in defining an arguments structure with chainable setters and default values. It's described in the C++ FAQ.

#include <iostream>

struct Args_add2var
{
    int     a_  = 0;
    int     b_  = 0;

    auto a( int const value )
        -> Args_add2var&
    { a_ = value; return *this; }

    auto b( int const value )
        -> Args_add2var&
    { b_ = value; return *this; }
};

auto add2var( Args_add2var const& args )
    -> int
{ return args.a_ + args.b_; }

auto main() -> int
{
    using Args = Args_add2var;
    int const c = add2var( Args().a( 5 ).b( 6 ) );

    using namespace std;
    cout << c << endl;
}

For a more general but restricted and IMHO pretty awkward solution, check out the Boost Parameters sub-library. Essentially the idea there is to declare global objects with the names of the parameters, to support the initialization-in-call notation. That's one issue that makes the scheme awkward, and as I recall it also has problems with constructors.

#include <boost/parameter.hpp>
#include <iostream>
using namespace std;

BOOST_PARAMETER_NAME( a )
BOOST_PARAMETER_NAME( b )

BOOST_PARAMETER_FUNCTION(
    (int),                  // 1. parenthesized return type
    add2var,                // 2. name of the function template
    tag,                    // 3. namespace of tag types, "tag" used by macro above
    (optional               // 4. two optional parameters, with defaults
        (a, (int), 0)
        (b, (int), 0)
        )
    )
{ return a + b; }

auto main() -> int
{
    int const c = add2var( _a = 5, _b = 6 );
    cout << c << endl;
}

Note that e.g. _a is not a global int variable, rather it's a global variable that represents the argument name.

In more general code it would be placed in a namespace along with the function.


For a more general discussion see my 2010 DDJ article "Pure C++ Options Classes". It does however suffer from Very Bad Formatting (it was nice as submitted), and the code is C++03. I would do things much more cleanly in C++11, but haven't looked at it since.

Upvotes: 0

Vijay Meena
Vijay Meena

Reputation: 695

We can only specify data-type for the function parameters during function definition and declaration. When we make function call, then we simply pass actual values for those function parameters/arguments. Thus your function call syntax int c = add2var(int a = 5, int b = 6.1); is completely wrong. I have not seen parameter type in function call in any of the language i am are of.

There are many other things which are wrong in your code.

  1. call int c = add2var(5, 6); instead of int c = add2var(int a = 5, int b = 6.1);, we can not specify data type here.
  2. passing floating point 6.1 for int is not good. it will be rounded off during function call.
  3. Using const in below code for function parameter is ok in case if you want to inform your API users that your function parameters will be unmodified. However, it does not protect anything when you are passing parameter as value. Nobody can change meaning of "5" and "6" right ?

    int add2var(const int a, const int b)
    {
        return a + b;
    }
    
  4. If your intention was to have default parameter then see below code.

    int add2var(int a = 5, int b = 6)
    {
       a + b;
    }
    
    int main()
    {
      add2var();         // result = 11, a will use default parameter 5 and b will use 6
      add2var(1);        // result = 7, b will use default parameter of 6
      add2var(2, 3); // result = 5, override default value for a and b
    }
    

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

There are two approaches. The first one is the following

int a;
int b;
int c = add2var( a = 5, b = 6);

The second one is the following where the function has default arguments

int add2var(const int a = 5, const int b = 6 );


int main()
{
    int c = add2var();
    //,,,

Upvotes: 2

Related Questions