user2178841
user2178841

Reputation: 859

Understanding statements in C

I am going through some C codes. Some of them are a little difficult to understand. For instance, what does following assignment do:

MY_TYPE my_var[3]={0};

MY_TYPE is some fixed point arithmetic type. I have not yet come across variables with [] brackets and assignment with {} around values.

That was too easy, I guess. So, what's advantage of defining

my_type my_var[3]={0};

over this:

my_type my_var[3];

Upvotes: 4

Views: 129

Answers (6)

haccks
haccks

Reputation: 106012

my_var[3] is a variable of type MY_TYPE which can store three values of same type(and known as Array) . Braces {} are used here as initializer. my_var[3] = {0} initializes its first element to 0.Rest of them are initialized to zero by self.

 MY_TYPE  my_var[3]; 

reserves three spaces in memory for the data of MY_TYPE. Whereas;

 MY_TYPE  my_var[3] = {0};

initializes all all these three spaces to 0.

Upvotes: 1

Nobilis
Nobilis

Reputation: 7448

It creates an array my_var of type MY_TYPE that is of size 3 and is initialised to all 0s (I suspect MY_TYPE is some sort of integer type). Note that only one initialisation is necessary for the rest to be init`ed too.

Also note that if you declare the array globally as opposed to within a block, then it will be initialised automatically and this MY_TYPE my_var[3]; will be enough.

Upvotes: 4

Kyle T
Kyle T

Reputation: 198

The advantage of using

my_type my_var[3]={0};

over

my_type my_var[3];

is that the first statement initializes the array. Without the initializer, your array will contain garbage values (whatever happened to be in those memory locations previously).

Upvotes: 1

Shumail
Shumail

Reputation: 3143

it's 1 dimensional Array of 3 Elements, initialized to 0. Technically, when you initialize one element of array, all other elements are automatically initialized to 0.

So 3 elements with 3 indexes:

my_var[0]=0;
my_var[1]=0;
my_var[2]=0;

My_TYPE can be int, char or any other data type. I hope this helps.

Read about Arrays more here: http://www.cplusplus.com/doc/tutorial/arrays/

Upvotes: 2

djf
djf

Reputation: 6757

MY_TYPE my_var[3]={0}; initializes the array my_var as:

my_var[0] = 0; my_var[1] = 0; my_var[2] = 0;

Upvotes: 2

macduff
macduff

Reputation: 4685

It's an array of 3 elements all initialized to 0.

Upvotes: 4

Related Questions