0
\$\begingroup\$

I have a valid code in C-style

int arr[10][10] = {0}; // all elements of array are 0

What is the optimal way to do the same for C++ style array?

My idea is

#include <array>

std::array<std::array<int, 10>, 10> arr = {0}; // is it correct?
\$\endgroup\$
1
  • 2
    \$\begingroup\$ This appears to be a general "best-practice" question, rather than a review of an existing function or program. \$\endgroup\$ – Toby Speight Mar 1 at 10:49
1
\$\begingroup\$

I feel this question is more suited for stack overflow, but I'll answer it anyway. In c++ the preferred way to do this is:

std::array<std::array<int, 10>, 10> arr = {}; // Without the 0

Also remember that static variables are zero-initialised anyway, so you wouldn't need to do that.

Because this is code review, I would suggest using a typedef to replace std::array<std::array<int, 10>, 10> to make your code more readable.

EDIT: As pointed out in the comments, using is much more powerful than typedef and more modern-c++ ish and one should preferably use it rather than typedef. It supports type aliasing templates and all other cool stuff, which is why it is preferable to use. ( Though never use using namespace ...;)

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I would suggest to use using instead of typedef as we want to use modern c++ practices. \$\endgroup\$ – Andreas Brunnet Mar 1 at 16:07
  • \$\begingroup\$ Thank you!!!!!! \$\endgroup\$ – swor Mar 1 at 16:59
  • 1
    \$\begingroup\$ @AndreasBrunnet Yes you are totally right. Will edit the answer. \$\endgroup\$ – SomeProgrammer Mar 1 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.