Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to implement a default value for a struct parameter

0.00/5 (No votes)
11 Dec 2003 2  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here