Default value for struct parameter

atoMerz picture atoMerz · Mar 9, 2013 · Viewed 17.6k times · Source

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.

Answer

SridharKritha picture SridharKritha · Jun 2, 2014

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());