Author: Zhu Jincan
During the National Day holiday, I read most of "Programmer self-cultivation-links, loading and libraries". P337 mentioned some implementation principles of the variable length parameter in C language, an example in the book is (I made some minor changes to the Code in the book, and the example compilation in the book is a little problematic ):
# Include <stdlib. h>
# Include <stdio. h>
# Include <assert. h>
# Include <stdarg. h>
/*!
* @ Brief calculates the sum of n integers, so there is no problem that the calculation result is out of bounds.
*
* @ Param [in] num the number of Integers to be calculated
* @ Return Calculation Result
*/
Long sum (int num ,...)
{
Assert (num> 0 );
Int * p = & num + 1;
Long ret = 0;
While (num --)
{
Ret + = * p ++;
}
Return ret;
}
Here we use the principle that the positions on the function Stack are arranged in sequence (that is, the addresses of indefinite parameters are in the high address direction of the variable num, and the function call Convention uses cdecl ). The following is the MyPrintf function that I use with MSDN to implement the same functions as the printf function in C language:
/*!
* @ Brief format the string and output it to the console.
*
* @ Param [in] pFormat format the string
* @ Return none
*/
Void MyPrintf (TCHAR * pFormat ,...)
{
Va_list pArg;
Va_start (pArg, pFormat );
Int len;
TCHAR * buffer;
Len = _ vsctprintf (pFormat, pArg) + 1; // _ vscprintf doesnt count, terminating
Buffer = (TCHAR *) (malloc (len * sizeof (TCHAR )));
_ Vstprintf_s (buffer, len, pFormat, pArg );
_ Putts (buffer );
Free (buffer );
Va_end (pArg );
}
Test code for the above two functions:
Int _ tmain (int argc, _ TCHAR * argv [])
{
Int x = 10;
Int y= 110;
Int z = 200;
Long Ret = sum (3, x, y, z );
MyPrintf (_ T ("% d % c % d"), 123, <, 456 );
MyPrintf (_ T ("% s"), _ T ("This is a string "));
Getchar ();
Return 0;
}
Test environment: Win XP + sp3, VS 2008 + sp1, unicode Character Set.
References:
1. "Programmer self-cultivation-links, loading and libraries", Yu jiazi/Shi fan/PAN aimin
2. MSDN (supporting VS 2008 + sp1)