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
Language: C++
Expertise: All
May 5, 1998

Fast, Efficient and Easy Way to Initialize Local Arrays

Fast, Efficient and Easy Way to Initialize Local Arrays By default, local data arrays created on the stack are not initialized; they contain garbage values. The easiest, most efficient and future-proof way to initialize them is as follows:
 
	void f() {
		char  name[100] = {0};  //all members initialized to '\0'
		float farr[1024] = {0}; //all members initialized to 0.0
		int   iarr[9999] = {0}; //all members initialized to 0.0
		void *pvarr[100] = {0};//all members initialized to NULL
	}//f()
And it even works for arrays of structs:
 
	struct A { char name[20]; 
			int age; /*other members*/ 
		  };

	void f() {
		A a[100] = {0};
		//...

	}//f()
The only exception is arrays of objects, which cannot be initialized like this if they have a user-defined constructor.
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