Calculations to position a text box next to another object I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa.
They should simply not overlap.

This is a code to position the text on some relatively good coordinates.

if(x &gt; (box_w + 20)) box_x = x - (box_w + 20);
else                            box_x = w + 20;
if(y &gt; (box_h + 20)) box_y = y - (box_h + 20);
else                            box_y = h + 20;
if(w &gt; width - (box_h + 20) || x + w + box_w + 20 &gt; width)
{
    box_x = 20;

    if(y &lt; box_h + 20)
    {
        box_y = h + 20;
    }
    else box_y = y - (box_h + 20);
}


x, y, w, h are the coords and dimensions for the object; box_x, box_y, box_w and box_y are for the text box and width/height is the dimension of the area.

Here is schematically how this code positions text (darker blue) near the object (lighter blue)


It is quite obvious that it could have been written much better.
To target performance, but more importantly - code space.

Can anyone suggest a better way to find good coordinates for the text box?
This is a definite candidate for using rect / point structures, but I don't know what the rest of your code-base looks like, so just talking about the algorithm alone, one approach would be:

void FindNonOverlappingPosition(
    uint canvasWidth, uint canvasHeight,
    uint x1, uint y1, uint width1, uint height1,
    uint width2, uint height2, uint spacing,
    uint* outX, uint* outY)
{
    // Position above if possible, below otherwise
    if (y1 &gt;= height2 + spacing)
        *outY = y1 - (height2 + spacing);
    else
        *outY = y1 + height1 + spacing;

    // Position left-aligned if content is closer to the left of the canvas, right-aligned otherwise
    if (x1 &lt; canvasWidth - width1)
        *outX = x1;
    else
        *outX = (x1 + width1) - width2;

    // Ensure that the box being positioned fits on the canvas
    if (*outX &lt; 0)
        *outX = 0;
    else if (*outX + width2 &gt; canvasWidth)
        *outX = canvasWidth - width2;
}


This fails in cases where an alignment according to those rules is impossible, such as the content taking up the entire height of the screen, or the text box being wider than the screen.  You could check for those cases and return an error code if desired.