General questions about the C++ code

Hi, as I've introduced myself, I'm trying to port Box2D to another language. 🙂

If you wouldn't mind me asking, I have a specific question about a piece of C++ code, and if I have any more questions I'll post them in this thread.

1)

b2BroadPhase.cpp line 450

b2Bound* bound = bounds + index;
b2Bound* prevEdge = bound - 1;

Alright, so I'm assuming bounds + index is the same as bounds[index], I hope that's correct.

What I don't understand is the second line, bound - 1, since bound is a pointer. What is this operation supposed to accomplish?

I've tried creating a sample C++ program to model this behavior, but I'm getting junk data from the bound - 1 operation.

Any help appreciated, thanks.

~ Clay
Hi Clay,

I use a lot of pointer arithmetic in Box2D. This is generally useful when dealing with arrays. In C/C++ when you add one to a pointer, you get the next element in the array. So if I have an array:

int myArray[4] = {1, 2, 3, 4};
int* elem = myArray + 2;

Here elem points to the 3rd entry of myArray, which has the value 3. If I do something like:

int* otherElem = elem - 1;

Then otherElem points to the second element of myArray, which has the value 2.

Now it doesn't matter how big an element of the array is, C/C++ will handle this for you. Suppose I had an array of structs. Adding 3 to the array pointer would give me the 4th element.

Subtraction from pointers works in the same way. It moves the pointer back towards the head of the array.

In the code you listed:

b2Bound* bound = bounds + index;
b2Bound* prevEdge = bound - 1;

These are equivalent to:
b2Bound* bound = &bounds[index];
b2Bound* prevEdge = &bound[index-1];

Original thread: https://box2d.org/forum/viewtopic.php?t=16