News:

Download Pelles C here: http://www.pellesc.se

Main Menu

Variadic functions

Started by Vortex, May 25, 2026, 12:46:11 PM

Previous topic - Next topic

Vortex

Here is a variadic function example, the VaFunc function calculates the sum of DWORDs.

.386
.model flat,stdcall
option casemap:none

ExitProcess PROTO :DWORD
printf PROTO C :DWORD,:VARARG
VaFunc PROTO C :DWORD,:VARARG

.data

f db 'Sum = %u',0

.data?

retaddr dd ?
i       dd ?

.code

start:

    push    7
    push    6
    push    5
    push    3
    call    VaFunc

    invoke  printf,ADDR f,eax

    invoke  ExitProcess,0

OPTION PROLOGUE:NONE
OPTION EPILOGUE:NONE

VaFunc PROC C x:DWORD,y:VARARG

    pop     retaddr
    pop     edx
    xor     eax,eax
@@:
    pop     ecx
    add     eax,ecx
    inc     i
    cmp     edx,i
    jne     @b
   
    push    retaddr
    retn

VaFunc ENDP
   
OPTION PROLOGUE:PrologueDef
OPTION EPILOGUE:EpilogueDef

END start
Code it... That's all...

Vortex

#1
Here is another version :

.386
.model flat,stdcall
option casemap:none

ExitProcess PROTO :DWORD
printf PROTO C :DWORD,:VARARG
VaFunc PROTO C :DWORD,:VARARG

.data

f db 'Sum = %u',0

.code

start:

    invoke  VaFunc,3,5,6,7

    invoke  printf,ADDR f,eax

    invoke  ExitProcess,0

OPTION PROLOGUE:NONE
OPTION EPILOGUE:NONE

VaFunc PROC C x:DWORD,y:VARARG

    xor     eax,eax
    mov     edx,DWORD PTR [esp+4]
@@:
    add     eax,DWORD PTR [esp+4*edx+4]
    dec     edx
    jnz     @b
    retn

VaFunc ENDP
   
OPTION PROLOGUE:PrologueDef
OPTION EPILOGUE:EpilogueDef

END start
Code it... That's all...

TimoVJL

Interesting code
Same with C
#include <stdio.h>
#include <stdarg.h>

int VaFunc(int, ...);

char f[] = "Sum = %u\n";

int __cdecl main(void)
{
    printf(f, VaFunc(3,5,6,7));
    return 0;
}

int VaFunc(int n, ...)
{
    int sum = 0;
    va_list args;
    va_start(args, n);
    for (int i = 0; i < n; i++)
        sum += va_arg(args, int);
    va_end(args);
    return sum;
}
May the source be with you