-3

I'm new to C++ but have had experience before with languages like java and I am starting off by making a simple command line Xs and Os game. When it came to creating the grid I found that I could initiate it in two different ways:

int grid[3][3] = {{0, 0, 0 },
                  {0, 0, 0 },
                  {0, 0, 0 }};

and:

int grid[3][3];
for (int x = 0; x < 3; ++x)
{
    for (int y = 0; y < 3; ++y)
    {
        grid[x][y] = 0;
    }
}

Is one method better than the other in any way and should I get into a habit of using one rather than the other?

Thanks

Nick stands with Ukraine
  • 6,365
  • 19
  • 41
  • 49

2 Answers2

2

In c++ you can write

int grid[3][3] = {};

This is enough see eg how does array[100] = {0} set the entire array to 0? and http://www.cplusplus.com/doc/tutorial/arrays/

Community
  • 1
  • 1
hivert
  • 10,396
  • 3
  • 29
  • 55
0

I like to use memset. It makes the code much nicer. Both the ways you suggested are valid but are more of a C dialect. A more object oriented approach could be using a matrix class with a constructor. Of course, in a real world you would probably use something like Boost for a general solution..

WeaselFox
  • 7,100
  • 7
  • 42
  • 73