2

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};
3
  • 5
    I think you messed up with the second one. There needs to be some name for the variable. Commented Apr 26, 2013 at 18:01
  • the second one works? Commented Apr 26, 2013 at 18:01
  • Thanks, @CoreyOgburn, typo corrected. Commented Apr 26, 2013 at 18:22

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

This is a nice comment, but don't answer the question. You might additionally answer it, or add in the @Deepu answer?
1

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 ;-)

Comments

1

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};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.