Why does he use CDECL

Oct 13, 2011 at 9:14pm
Hello everyone. Not too long ago I got started learning to program in windows. The book I am learning from had a program that made a message box which displayed the width and height of the display in pixels. I understand the pretty much all of the code, but I am not quite sure why he used the CDECL calling convention for MessageBoxPrintf(). Here is the whole souce code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>

int CDECL MessageBoxPrintf (TCHAR * szCaption, TCHAR * szFormat, ...)
{
	TCHAR szBuffer[1024];
	va_list pArgList;

	va_start (pArgList, szFormat);

	_vsntprintf(szBuffer, sizeof(szBuffer) / sizeof(TCHAR), szFormat, pArgList);

	va_end(pArgList);

	return MessageBox(NULL, szBuffer, szCaption, 0);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	PSTR szCmdLine, int iCmdShow)
{
	int cxScreen, cyScreen;
	cxScreen = GetSystemMetrics(SM_CXSCREEN);
	cyScreen = GetSystemMetrics(SM_CYSCREEN);

	MessageBoxPrintf(TEXT("Screen Size"), TEXT("The screen is %i pixels by %i pixels"), cxScreen, cyScreen);

	return 0;
}
Oct 13, 2011 at 9:26pm
The C Programming Language has a particular calling convention. One of its features is arguments are pushed from left to right and the caller pops the stack on return.

Why? This is to support variable numbers of arguments in functions like printf.

When you call printf, it uses the format string to decide how many arguments were pushed and uses extactly that. The caller can in fact pass more arguments than specified, but the extras are ignored.

Becuase only the caller knows how many arguments were pushed onto the call stack, only the caller can pop them.

When Microsoft developed Windows, machine resources were a constant worry. Someone noticed that if the called function pops the stack, then you don't get all the callers popping the stack and saved a considerable amount of space. So the Pascal calling convention was used to do just that.

Pascal pushes arguments right to left and the called function/procedure pops the stack. The cost is that the variable number of arguments is no longer supported.

So cdecl and pascal were introduced to Windows C compilers to indicate the calling convention for a function. If you don't specify it, you get cdecl by default.

WIN32 introduced stdcall, which is pushies args left to right with the called popping the stack.
Oct 14, 2011 at 7:33am
ah ok, thanks for the explanation.
Topic archived. No new replies allowed.