不定参数列表的小练习:-)

对于cstdarg宏用于不定参数列表不是很熟悉,做个小练习:-)

#include <iostream>
#include <cstdarg>

typedef int Elem;
using namespace std;
Elem MaxInt(int n,...)
{
 va_list ap;
 Elem max,tmp;
 int i;
 va_start(ap,n);
 if(n<1)
 {
  cout<<"参数错误!";
  exit(-1);
 }
 for(i=0;i<n;i++)
 {
  tmp=va_arg(ap,Elem);
  if(tmp>max)
   max=tmp;
 }
 va_end(ap);
 return max;
}

int main()
{
 cout<<"1.最大值为"<<MaxInt(4,10,0,3,-11)<<endl;
 cout<<"2.最大值为"<<MaxInt(6,10,0,3,-11,1004,5656)<<endl;
 return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *