0

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 : ')'

LiuHao
  • 412
  • 1
  • 6
  • 16
  • 2
    Because that's the wrong syntax. You simply call your function `add2var(i5,6.1);` – πάντα ῥεῖ May 09 '15 at 07:29
  • 1
    @πάνταῥεῖ So we can't initialize arguments in parentheses of calling functions? – LiuHao May 09 '15 at 07:35
  • @LiuHao you don't need to. You must just supply the arguments in the right order. – wimh May 09 '15 at 07:37
  • If you need `a` and `b` otherwise, initialize them outside of the function call, yes. – πάντα ῥεῖ May 09 '15 at 07:37
  • @πάνταῥεῖ@Wimmel So I guess the reason is that we don't need to initialized `a` and `b` in parentheses because they are local variables and will die and be undefined after the execution of the function? – LiuHao May 09 '15 at 07:39
  • Along those lines. The variables will be built when the stack is set up for the add2var function and only exist as local variables in the add2var function. Since main never uses those numbers except in the function call, there is no point to wasting memory allocating them in main and then allocating copies of them in add2var. – user4581301 May 09 '15 at 07:50
  • @LiuHao What about picking up a good book [from here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn the basics. – πάντα ῥεῖ May 09 '15 at 07:51
  • @πάνταῥεῖ Actually I am a newbee to C++ and am learning C++ Primer. Because I'm moving from MATLAB to C++ so sometimes I will be confused and may ask some very basic questions. Sincere thanks for your comment.^-^ – LiuHao May 09 '15 at 07:57

3 Answers3

2

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();
    //,,,
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

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
    }
    
Vijay Meena
  • 683
  • 1
  • 7
  • 12
0

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331