atoMerz
atoMerz

Reputation: 7672

Default value for struct parameter

Let's say I have the following struct:

struct myStruct
{
 int x;
 int y;
 int z;
 int w;
};

I want to initialize this struct to a default value when calling the following function. If it helps I'm looking for a simple zero initialization.

void myFunc(myStruct param={0,0,0,0})
{
 ...
}

This code however gives me compile error. I've tried VS2003 and VS2008.

NOTE: I have looked at other answers mentioning the use of constructor. However I want the user to see what values I'm using for initialization.

Upvotes: 6

Views: 26446

Answers (2)

SridharKritha
SridharKritha

Reputation: 9621

Adding default constructor in to your myStruct will solves your problem.

struct myStruct {
   myStruct(): x(0),y(0), z(0), w(0) { }   // default Constructor
   int x, y, z, w;
};

Function declaration:

void myFunc(myStruct param = myStruct());

Upvotes: 7

AnatolyS
AnatolyS

Reputation: 4319

For modern C++ compilers which fully implement value-initilization it is enough to have the following value-initialized default value to zero-initiliaze data members of the myStruct:

myFunc(myStruct param=myStruct())

For other compilers you should to use something like this:

myStruct zeroInitilizer() {
   static myStruct zeroInitilized;
   return zeroInitilized;
}
myFunc(myStruct param=zeroInitilizer())

To avoid compiler specifics conside to use http://www.boost.org/doc/libs/1_53_0/libs/utility/value_init.htm

Upvotes: 3

Related Questions