2003

Grusel++ of the month

Home
Download Source
/******************************************************************************/
/*                                                                            */
/*                                                            FILE: april.cpp */
/*                                                                            */
/*  An example for a function with variable arguments                         */
/*  =================================================                         */
/*                                                                            */
/*  Compiled and tested with Visual C++ 6.0                                   */
/*                                                                            */
/*  V1.00   30-APR-2003   P. Tellenbach   http://www.heimetli.ch/             */
/*                                                                            */
/******************************************************************************/

#include <iostream>

using namespace std ;

void print( char *pc )
{
   cout << *pc ;

   if( *pc != '\n' )
      print( pc + sizeof(int) ) ;
}

void printlist( char ch, ... )
{
   print( &ch ) ;
}
   

int main()
{
   printlist( 'H','e','l','l','o',' ','w','o','r','l','d',' ','!','\n' ) ;

   return 0 ;
}

Update 30. April 2023

This program did not produce the expected output. The pointer arithmetic was questionable from the beginning and therefore I rewrote it using va_list.

/******************************************************************************/
/*                                                                            */
/*                                                            FILE: april.cpp */
/*                                                                            */
/*  An example for a function with variable arguments                         */
/*  =================================================                         */
/*                                                                            */
/*  Compiled and tested with Visual C++ 6.0                                   */
/*                                                                            */
/*  V1.00   30-APR-2003   P. Tellenbach   http://www.heimetli.ch/             */
/*                                                                            */
/******************************************************************************/

#include <iostream>
#include <cstdarg>

using namespace std ;

void print( char ch, va_list args )
{
   cout << ch ;

   if( ch != '\n' )
   {
      ch = static_cast<char>( va_arg(args,int) ) ;
      print( ch, args ) ;
   }
}

void printlist( char ch, ... )
{
   va_list args ;
   va_start( args, ch ) ;

   print( ch, args ) ;

   va_end( args ) ;
}
   

int main()
{
   printlist( 'H','e','l','l','o',' ','w','o','r','l','d',' ','!','\n' ) ;

   return 0 ;
}