Variable Parameter usage (C ++ and C)

Source: Internet
Author: User

// Variable Parameter usage in C ++
# Include <stdio. h>
# Include <stdarg. h>

Int Openfilearray ( File *** Array , Char * Mode , Char * Filename , ...)
{
Char * Pname= Null ;
Int Nrfiles = 0 ;
Int Arrayindex = 0 ;
If ( Filename = Null ) {
Return 0 ;
}
// Create an index using typedef In the parameter table
Va_listlistindex ;
// Initialize the macro of the first parameter index in the parameter table
Va_start ( Listindex , Filename );

Do{
Nrfiles++;
// Obtain the macro of the next parameter in the parameter table
Pname=Va_arg(Listindex,Char*);
}While(Pname! =Null);

*Array=NewFile*[Nrfiles+1];

// Open files
Pname = Filename ;
Va_start ( Listindex , Filename );
Do {
If (! ((* Array )[ Arrayindex ++] = Fopen ( Pname , Mode ))) {
(* Array )[ Arrayindex - 1 ] = Null ;
Return 0 ;
}
Printf ( "Had open file: % s \ n" , Pname );
Pname = Va_arg ( Listindex , Char *);
} While ( Pname ! = Null); // There is a problem

(*Array)[Arrayindex]=Null;

Return1;
}

Void Main ( Void )
{
File ** Array ;
Int Fp = Openfilearray (& Array , "R" , "1.txt" , "2.txt" , "3.txt" );

If ( Fp = 1 ) {
Printf ( "\ Nopen file successfully! \ N" );
}
// Close the files
Int I = 0 ;
While ( Array [ I ] ! = Null ) {
Fclose ( Array [ I ++]);
}
Delete [] Array ;
}
// Use variable parameters in C #
// If you do not need the Params keyword, you need to use new object [] {arg1, arg2} when calling the parameter}
Class Program
{
Public Static Int Sumwithvariableparams ( Params Int [] ARGs )
{
Int Sum = 0 ;
For ( Int I = 0 ; I < ARGs . Length ; I ++)
{
Sum + = ARGs [ I ];
}
Return Sum ;
}
Static Void Main ( String [] ARGs )
{
System . Console . Writeline ( "Sum (1, 2, 3, 4, 5) =" + ( Sumwithvariableparams ( 1 , 2 , 3 , 4 , 5 )). Tostring ());
System . Console. Writeline ( "Sum (33, 22) =" + ( Sumwithvariableparams ( 33 , 22 )). Tostring ());
System . Console . Readline ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.