65.9K
CodeProject is changing. Read more.
Home

How to implement a default value for a struct parameter

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.47/5 (34 votes)

Dec 12, 2003

viewsIcon

141704

How to implement a default value for a struct parameter.

Introduction

Someone asked me how to implement a default parameter value for a struct. He wanted to make it possible to make the following calls:

MyStruct st = {200,50);

foo();   // No parameters means the default ones
foo(st); // Use the parameters passed

He had tried the following:

struct MyStruct 
{ 
    int a; 
    int b;

};
 
void foo(MyStruct st={100,100}) 
{
    cout << st.a << " " << st.b << endl;
}

The compiler (VC 6) however didn't compile this.

Solutions

You can use a constructor in your struct. It's not really nice but it will work.

struct MyStruct 
{
    MyStruct(int x, int y)
    {
        a = x;
        b = y;
    }
    int a; 
    int b;

};

void foo(MyStruct st=MyStruct(100,100)) 
{
    cout << st.a << " " << st.b << endl; 
}

The second solution, I like a little more:

struct MyStruct 
{
    int a; 
    int b;
};
static const MyStruct stDefValue = { 100, 100 };

void foo(MyStruct st=stDefValue) 
{
    cout << st.a << " " << st.b << endl;
}

Conclusion

It's not a big deal and you may find it not nicely programmed in an OO way, but it is handy to know when you want to do something like this.