Search code examples
c++functionpointerspositioncursor-position

C++: Why must some functions be placed in if statements?


I'll be referencing this answer: Get current cursor position

The working code:

    HWND hwnd;
    POINT p;
    if (GetCursorPos(&p))
    {
        //cursor position now in p.x and p.y

    }
    if (ScreenToClient(hwnd, &p))
    {
        //p.x and p.y are now relative to hwnd's client area
        cout << p.x << p.y;
    }

This compiles but crashes when I click in the window:

    HWND hwnd;
    POINT p;
    if (GetCursorPos(&p) && ScreenToClient(hwnd, &p))
    {
        //cursor position now in p.x and p.y
        cout << p.x << p.y;
    }

This also compiles but crashes when I click in the window:

    HWND hwnd;
    POINT p;
    GetCursorPos(&p);
    if (ScreenToClient(hwnd, &p))
    {
        //cursor position now in p.x and p.y
        cout << p.x << p.y;
    }

Why? Are these functions unusual in any way?

Does it have something to do with the fact that pointers are involved?

How does placing these functions in if statements change how they run?


Solution

  • if (GetCursorPos(&p) && ScreenToClient(hwnd, &p)) is quite pernicious, but strangely elegant.

    Due to the short-circutting nature of the && operator, ScreenToClient(hwnd, &p) will only be called if GetCursorPos(&p) runs successfully (i.e. returns something that converts to true). The latter, if successful, also happens to set p to something valid for the subsequent ScreenToClient call.

    The enclosing if block is only ran if both functions are successful.

    Your crash could well be due to your hwnd being uninitialised.