Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Feb 17, 1998

A Simple, Easy, and Efficient Way to Initialize Structs

Struct instances created on the stack are uninitialized (i.e., contain garbage values). The easiest, most efficient, and future-proof way to initialize them is:
 
struct  PlainData {
char [20] name;
long ID;
char [15] phone;
//... other fields as many as you like 
};

int main()
{
	PlainData data = {0};  
//automatic initialization of the rest 					
//of data to binary zeroes is 						
//guaranteed both for C and C++
}
This is a much better way than manually assigning values to all the fields of the struct (which may also turn into a maintenance nightmare when new struct members are added or deleted) and it is at least as efficient as a memset() call—usually much more efficient.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date