3

What is the difference between declaring a 2D array in C++ like this:

int mp[3][3]={{0,2,1},
              {0,2,1},
              {1,2,0}};

And this?

int mp[3][3]={0,2,1,
              0,2,1,
              1,2,0};

Is the above an array where all 3 elements are arrays themselves while the bottom one is an array of non-array elements or are both read by the compiler as the same?

2
  • 3
    What language? Some handle it differently. Commented Mar 3, 2013 at 21:44
  • @A--C in C++. I edited to add that I need to understand it in C++ Commented Mar 3, 2013 at 21:45

2 Answers 2

6

They're equivalent. The first one is a completely braced form. When the interpretation is unambiguous (such as in the second form), the standard allows eliding the braces.

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

5 Comments

I ask because my program was giving me different results. I'm guessing I changed something else and forgot about it.
@Chase what is your compiler?
@Grijesh Chauhan Microsoft Visual Studio C++ 2010 Express
As per [dcl.init.aggr]§10, they should be equivalent. §11 even has an example matching your case almost exactly.
@Angew Before I forget, thank you. I was able to find the real problem with my program after you clarified this for me.
1

Both are same you can access elements for matrix using following loop:

for (i=0;i<3;i++)   
     for(j=0;j<3;j++)     
        printf("%d ",mp[i][j] );

One difference in when you give braces in first case then first argument can be omitted like:

int mp[][3]={{0,2,1},
              {0,2,1},
              {1,2,0}};

But C++ compiler will give you warning: missing braces around for second type of declaration.

EDIT:
As you commented: my program was giving me different results

I have written a code. working fine on C++ (gcc-4.7.2). Check here

1 Comment

Um, some C++ compilers (and, I assume, some C compilers) will give a warning.

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.