Reputation: 59
I've been looking at this for a while and I have some ideas on what this code could be doing, but I'm not sure if I correctly understand what the syntax of the code does.
The code iterates through a 2D array of unsigned chars, its meant to fill the array with 0's unless the spot in the array represents; the bottom, or the sides. If that is the case fill the spot in the array with a 9 instead.
The part I'm confused about is the statement (pField[y*fieldWidth + x] =
) I believe this is a conditional statement, I understand the logic after, my question is specifically about this conditional, how should it be interpreted using if statements if possible?, If its not a conditional statement, what kind of statement is it?
pField = new unsigned char[fieldWidth*fieldHeight]; // Create play field buffer
for (int x = 0; x < fieldWidth; x++) // Board Boundary
for (int y = 0; y < fieldHeight; y++)
pField[y*fieldWidth + x] = (x == 0 || x == fieldWidth - 1 || y == fieldHeight - 1) ? 9 : 0;
Upvotes: 1
Views: 129
Reputation: 598124
The code is using a 2-dimensional array that is allocated in memory as a 1-dimensional array. The expression y*fieldWidth + x
is calculating a 1D array index from a pair of 2D indexes.
The array represents a rectangle. The code is assigning a 9
to the 1D array elements that represent the rectangle’s left, right, and bottom edges (but not the top edge), and a 0
in the 1D array elements representing the rest of the rectangle.
For example, a 5x5 rectangle would look like this:
9 0 0 0 9 9 0 0 0 9 9 0 0 0 9 9 0 0 0 9 9 9 9 9 9
The corresponding 1D array elements would look like this:
x = 0 1 2 3 4 | 0 1 2 3 4 | 0 1 2 3 4 | 0 1 2 3 4 | 0 1 2 3 4
y = 0 0 0 0 0 | 1 1 1 1 1 | 2 2 2 2 2 | 3 3 3 3 3 | 4 4 4 4 4
---------------------------------------------------------
pField[] = 9 0 0 0 9 9 0 0 0 9 9 0 0 0 9 9 0 0 0 9 9 9 9 9 9
The ternary ?:
operator can be rewritten using an if
statement like this:
int value;
if (x == 0 || x == fieldWidth - 1 || y == fieldHeight - 1)
value = 9;
else
value = 0;
pField[y*fieldWidth + x] = value;
Upvotes: 4
Reputation: 487
This code allocates space for a 2D array into a 1D array and then sets each element in the array. Regarding specifically the code you question, on the left hand side of the array the logic translates from 2D indices into 1D index. On the right hand side of the assignment the value is calculated by concatenating boolean predicates into a resulting boolean value that is then selected between returning 0 or 9 via a ternary operator and is wrote to the unsigned char array element.
Upvotes: 1