Archived

This topic is now archived and is closed to further replies.

mickey

is there a way to initialize all datas in a struct at only one statement?

Recommended Posts

mickey    100
for example i have this struct mystruct { bool data1; bool data2; bool data3; bool data4; } well, how will i initialize that all to false in one statement? thanks!

Share this post


Link to post
Share on other sites
Fruny    1658
You can do that, but only when you are defining the variable

mystruct a = { false, false, false, false }; // ok
mystruct b;
b = { false, false, false, false }; // not ok

Or, a trick... (works with arrays, maybe not with structs, may not be portable...)

mystruct c = { false }; // all other members implicitely set to zero (i.e. false in this case)

Share this post


Link to post
Share on other sites
zedzeek    529
100% unsafe but it should work for the above case

struct mystruct
{
bool data1;
bool data2;
bool data3;
bool data4;
}

mystruct ms;
memset( &ms.data1, 0, 4 ); // 0 ==false

Share this post


Link to post
Share on other sites
capn_midnight    1707
skip the struct, go with a class
  
class CMyClass{
private:
bool data1, data2, data3, data4;
pubilc:
CMyClass();
};
CMyClass::CMyClass()
{
data1=data2=data3=data4=FALSE;
}
int main(void)
{
CMyClass a; //all data initialized to FALSE;

return 0;
}

Share this post


Link to post
Share on other sites
Promit    13246
Disregard above and go with this much more slick solution:
  
struct mystruct
{
bool data1, data2, data3, data4;
inline mystruct() { data1=data2=data3=data4=false; }
}

structs can have constructors!

-----------------------------
The sad thing about artificial intelligence is that it lacks artifice and therefore intelligence.

Share this post


Link to post
Share on other sites