• Advertisement

Archived

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

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

This topic is 5834 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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

  • Advertisement