1

In a Visual Studio MFC app, I have the following function:

BOOL CSomeDialog::OnToolTipNotify(UINT id, NMHDR* pNMHDR, LRESULT* pResult)
{
    ...

    // Get the window handle ...
    const HWND hControl = (HWND)pNMHDR->idFrom;

    ...
}

Visual Studio's code analysis reports:

Warning C26462  The value pointed to by 'hControl' is assigned only once, mark it as a pointer to const (con.4).

I do like code analysis to report on variables that can be consts (I think it clarifies the code's intent), however I don't understand why the above code generates this message. I suspect I am declaring a const pointer rather than a pointer to a const, but I'm unsure of the fix (I've tried "HWND const hControl").

Thanks.

Steve A
  • 1,798
  • 4
  • 16
  • 34
  • 1
    Does this answer your question? [C++ typedef interpretation of const pointers](https://stackoverflow.com/questions/2253738/c-typedef-interpretation-of-const-pointers) – GSerg Aug 26 '20 at 21:55
  • @GSerg, that's a similar concept (the order of "const" vs the pointer declaration), but it doesn't explain the issue relative to an HWND variable. – Steve A Aug 27 '20 at 16:14
  • It's not the order of const, it's the fact that `const HWND hControl` is not the same as `const void* hControl`. – GSerg Aug 27 '20 at 17:21
  • If it was `typedef void* HWND`, a `const HWND` would be a `void* const`, @GSerg. As a side note, that's why I always put the `const` to the right of what is supposed to remain constant, not on the left. – Ulrich Eckhardt Dec 13 '20 at 15:05
  • Can you please extract and provide a [mcve]? I'm not 100% sure that there is something else in the code you don't show that causes these issues. Also, what C++ type does `HWND` eventually resolve to? – Ulrich Eckhardt Dec 13 '20 at 15:06

1 Answers1

2

This is what I would do:

#define CHWND const HWND__ * const
CHWND hControl = (CHWND)pNMHDR->idFrom;

Alternatively you could this:

typedef const HWND__* const CHWND;
CHWND hControl = (CHWND)pNMHDR->idFrom;

Or this:

using CHWND = const HWND__* const;
CHWND hControl = (CHWND)pNMHDR->idFrom;
Bix
  • 21
  • 3
  • Doesn't work. `HWND` is an opaque handle type. Doing it your way would make it impossible to initialize a `HWND` from a `CHWND`. Don't get me started with the `#defined` which is a really bad substitute for a `typedef`, btw. – Ulrich Eckhardt Dec 13 '20 at 15:08