reinterpret_cast is safe when using DialogBox ?

I've stepped into Dialog Boxes,and the fourth argument lpDialogFunc [in, optional]
Type: DLGPROC.

I've casted the fourth like this :

1
2
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DLGFIRST),
	          hWnd, reinterpret_cast<DLGPROC>(DlgProc)));


Now is DlgProc :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
LRESULT CALLBACK DlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	switch(Msg)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		switch(wParam)
		{
		case IDOK:
			EndDialog(hWndDlg, 0);
			return TRUE;
		}
		break;
	}

	return FALSE;
}


DlgProc is a function pointer,of type LRESULT* (???) and then cast to DLGPROC* (???),and is the cast safe (???)


(???) are 3 questions I really need to make things clear.Thanks in advance.

You shouldn't need a cast for the fourth parameter.

DialogBox(hInstance, MAKEINTRESOURCE(IDD_DLGFIRST), hWnd, DlgProc);

should compile without warning, if your DlgProc is declared correctly.

Andy

PS If your function is declared correctly, the cast is "safe" as you're just casting your function back to the same type. But the cast could hide a problem, e.g. you forget the CALLBACK and end up using a __cdecl function when a __stdcall one -- which is what CALLBACK is equivalent to -- is expected. and hit stack related problems. So, overall, it's a bad thing to do.
Last edited on
Agreed: Rule of thumb: If you have to cast, you're probably doing it wrong. It is not a golden rule, so it doesn't apply 100% of the time, but it does make you think twice why you need a cast. If you can convince yourself that there is just no other way of doing it, then do the type cast, but only after you have seriously convinced yourself that it is in fact needed.
Topic archived. No new replies allowed.