mushroom
mushroom

Reputation: 1945

C array initialisation, are both acceptable?

This might seem simple, but I can't seem to find it when I search around.

I just want to find out if these two ways of initialising and array are the same, or is there a preferred way of doing it? What does the ANSI C standard say about this?

int a[3] = {1, 2, 3};

and...

int a[] = {1, 2, 3};

Upvotes: 2

Views: 143

Answers (4)

M0X2
M0X2

Reputation: 55

Adding the size of array is usually used when you want more room in your array and you just want to set some of them in declaration. In other cases, I personally prefer the second notation because it prevents from taking more size or a compile error due to low size, just because of your mistaken value for array size. If you have a const value for size and you are using it couple of times then the first notation will be more reliable. So your answer would be it depends on your program.

int a[CONST_SIZE] = {1,2,3};
int a[] = {1, 2, 3};

Upvotes: 1

Ömer Faruk Almalı
Ömer Faruk Almalı

Reputation: 3822

First one works but the second one is going to give syntax error. Also if you use sth. like this:

int a[5]={1};

Other 4 integers will be initialized as 0.

Upvotes: 5

qwertz
qwertz

Reputation: 14792

I think you did something wrong with the second one! But if the second one would be:

int b[] = {1, 2, 3};

The two lines would have the exact same result.
The array size of the two arrays would be 3 * sizeof(int).
It's your decision which line you use. The advantage of the first line is, that you can see the array size easily without counting the elements in the brackets but it's using 1 more byte in your source code file ;-)

Upvotes: 1

Deepu
Deepu

Reputation: 7610

int a[3] = {1, 2, 3}; is O.K.

But int [] = {1, 2, 3}; is definitely a syntax error.

But if your question is regarding int a[] = {1, 2, 3}; then that is a valid statement.

Upvotes: 7

Related Questions