-1

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?

Aaron Franke
  • 3,268
  • 4
  • 31
  • 51

2 Answers2

4

It doesn't change how the functions run. Many functions return a boolean value indicating whether the operation succeeded or not. By enclosing the function call in an if, you're automatically checking if the operation succeeded.

   if(functionReturningSuccess(params))
   {
      //assume the operation succeeded
   }
   else
   {
      //report error
   }
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 2
    How does this answer why `if (GetCursorPos(&p) && ScreenToClient(hwnd, &p))` crashes when it does not if it is two separate if blocks? – NathanOliver Jul 13 '16 at 15:43
  • @NathanOliver there are many questions in the question. This appears to be an answer to another of the questions, than you refer to. – eerorika Jul 13 '16 at 15:52
3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • However, as OP says, `if (GetCursorPos(&p) && ScreenToClient(hwnd, &p))` still crashes when he clicks the window – buld0zzr Jul 13 '16 at 15:55