I'm doing a C++ tutorial that teaches the language through game development. Within this tutorial there's a piece of code which I do not understand how it works.
First an enum class is declared and an array is initialized:
enum class side {LEFT,RIGHT, NONE};
side branchPositions[NUM_BRANCHES]; / which is a const variable and has the value of 6
Within the main function I have this code:
for (int i = 0; i < NUM_BRANCHES; i++)
{
float height = i * 150;
if (branchPositions[i] == side::LEFT)
{
branches[i].setPosition(610, height);
branches[i].setRotation(180);
}
else if (branchPositions[i] == side::RIGHT)
{
branches[i].setPosition(1330, height);
branches[i].setRotation(0);
}
else
{
branches[i].setPosition(3000, height);
}
}
What it does is, it updates the position of the branch sprites.
When running the code, I get the following result:

After the following function is added and called
void updateBranches(int seed)
{
for (int j = NUM_BRANCHES - 1; j > 0; j--)
{
branchPositions[j] = branchPositions[j - 1];
}
srand((int)time(0) + seed);
int r = (rand() % 2);
switch (r)
{
case 0:
branchPositions[0] = side::LEFT;
break;
case 1:
branchPositions[0] = side::RIGHT;
break;
default:
branchPositions[0] = side::NONE;
break;
}
}
the branches get distributed randomly, like so:

Now, I do not get why this is. I do understand why the branch at position 0 is either left, right or not visible due to the switch statement. But I don't understand how the for loop in the function interacts with the array and why this leads to the behavior shown in image 2.
I also do not understand what values are stored in the array and what the connection with the enum class is.
Could somebody please clarify ? Thanks
branchPositionsarray before callingupdateBranches? You may just be reading garbage from memory.defaultcase inupdateBranchesis unreachable. 2) Usingtime(0) + seeddefeats the purpose of being able to specify a seed at all - seeds are used to make your random numbers reproducible, but thetime(0)counteracts that.