Friday, May 24, 2013

Rewinding Variadic Lists

/* Written as a personal challenge; it is possible to rewind a Variadic list; in fact it's extremely easy, as it is based on the use of pointers, which have a definitive size in memory, so you can move up and down the list simply by adjust the pointer of the list.  In this example this was accomplished using the sizeof function and adjust the list pointer by iterations of this (I believe it's 4 bytes, but I might be wrong about that).  I haven't tested this with any other type in the list (chars*, doubles, etc) but it seems like it aught to work.
 */
#include <iostream>
#include <stdarg.h>
using namespace std;
void out(int sou,...);
int main(){
    int i=0;
    out(i,3,4,5,6,0);
    cin >> i;
    return 0;
}
void out(int sou,...){
    int r=0,i=1;
    va_list test;
    int start=sizeof(test);/*this grabs the size of the pointer*/
    va_start(test,sou);
    while(r=va_arg(test,int)){
        cout << "int = " << r << ":"<<(int)test << endl;
        i++;/*this counts the number of parameters passed to the function*/
        }
    test-=start*i;//this rewinds the pointer to the start of the list
    while(r=va_arg(test,int)){
        cout<<r<<endl;
        }
    va_end(test);
    va_list test2;
    va_start(test2,sou);/*this is just provided as a second method of "rewinding the list" though is less efficient*/
    while(r=va_arg(test2,int))cout << "int = " << r << ":"<<(int)test << endl;
    va_end(test2);
}

No comments:

Post a Comment