Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 715
atoMerz Avatar asked Mar 09 '13 06:03

atoMerz


2 Answers

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());
like image 138
SridharKritha Avatar answered Oct 17 '22 16:10

SridharKritha


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

like image 25
AnatolyS Avatar answered Oct 17 '22 14:10

AnatolyS