Monday, November 25, 2013

Unnamed function parameters

There could be unnamed parameters in a function, for example, void f(int a, int);  The second parameter is an unnamed parameter.

Basically the reason you need them is to use them as place holder for future.

Even though an unnamed parameter doesn't have a name, however, when you call the function you need to specify a value for it, the same normal way when you are dealing with normal named parameters.There is nothing special about them, except that you don't do anything with them inside the function because they don't have names and you are not able to interact with something that doesn't have a name.

In some cases, for example post increment/decrement operator, even you don't provide values for unnamed parameters, however, compiler has already done that for you by providing the default value of whatever type that unnamed parameters belong to. So don't be fooled by that.

In short, either you or compiler need to provide values for unnamed parameters.


Code:
void f(int a, int){    cout << "a is " << a << endl;}

class ABC
{
public:
    ABC(int a){this->a = a;}
    int operator++(int)   {        return a++;    }
    int operator()()    {        return a;    }
private:
    int a;
};

 Test code:

    // You specify the value for the unnamed parameter
    f(2,3000);
    ABC a(3);
    cout << a() << endl;
    // Compiler specifies the value for the unnamed parameter,
    // which is the default int value in this case.
    cout << a++ << endl;
    cout << a() << endl;


Result:
a is 2
3
3
4

No comments:

Post a Comment