ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How Do I Write C++ VARIADIC Functions using va_start, va_arg, va_end Macros?

Updated on May 15, 2018

1. Variadic Function

Variadic function means a C/C++ function which takes a variable number of arguments. Think about the printf() function, which can take one are more parameters. Can you imagine how it can be implemented? Function overloading! No. Here comes the Variable Argument list in the picture. The C printf function collects the arguments in a list and inside the function, the list will be read to get all the parameters.

In this hub, let us write an Example, which will calculate the summation of numbers passed as a variable number of argument by raising it to power x passed as a standard parameter.

2. Syntax for Variadic Function

Let us say, you want to get minimum from the list of numbers passed as an individual argument to a function. Have a look at the function usage:


Calling a Variadic Function
Calling a Variadic Function | Source

In the first statement, a long variable is declared. In the next statement, a function GetMin is called with five parameters. In the third statement, the same function is called with eight parameters. Here, the function GetMin is Variadic as it accepts the different number of parameters. So when a function is a Variadic function, you can pass N number of parameters to it. In the above example, the first parameter tells, how many numbers of parameters passed to the function followed by actual parameters among which minimum should be picked. Here, the first parameter is Standard Parameter and next coming parameters are called “Parameter List”. Let us see how this function can be declared.

Have a look at the below picture:

Variadic Function Syntax Explanation
Variadic Function Syntax Explanation | Source

In the above picture, you are seeing a declaration of a variadic function. The function returns long data type and the name of the function is GetMin. The first parameter “nop” is called a standard parameter or named parameter. The three dots which can be also called as ellipsis signifies the variable argument list. That means, after passing the standard argument, you can pass ‘N’ number of arguments as shown in the first picture.

3. Va_start va_arg va_end

These macros are used to process the variable argument list passed to the function. Va_start will perform the population of va_list with the passed-in variable argument list. Va_arg will read the parameter from the current position in the list and advances the position to next one. Va_end is used to clear the va_list stating that the arguments are processed in the called function. Have a look at the below picture:

va_list and ...
va_list and ... | Source

Here, the ellipsis states the variable argument list and during the va_start call, the parameters in the placeholder of ellipsis are filled into the va_list.

4. Variadic Function – An Example

1) First, the required headers are included in the cpp file. The header file math.h is included to use the pow function which raises a given number to a power say x. To process the variadic argument list, the header file stdarg.h is included in the file. Below is the code change:

//1.0 Required includes
# include <stdio.h>
# include <stdarg.h>
# include <math.h>

2) The function Power_Summation is used to compute the summation by raising each number to a power of second passed-in parameter. In the below-given code, the first parameter “No_Params” tells how many variadic parameters are passed to the function. The second parameter is used to raise each number to power N. After raising the power of individual argument they are summed up.

The param_list used here holds the variable number of arguments passed to the function. This list is initialized by using the va_start macro. The first parameter expected by the macro is the va_list to hold the variable number of arguments. The second parameter passed to the macro is the last standard parameter, which is preceding the variadic arguments. In our case it is RaiseTo. Now the macro knows where the variadic parameter starts, as it knows where the standard parameters end.

A for loop is formed by making use of the first parameter passed to the function and in each iteration, the macro va-arg is used to extract the parameter one by one. A call will extract the variable in a current position and moves the extractor to next position in the variadic list (va_list). Note that va_arg expects the va_list as well as the data type of the parameter. In our case, we are going to pass float/double value as arguments and hence double is passed as the second parameter to the va_arg list. After extracting the parameter a cumulative summation is performed. The macro va_end is used to clear the list. The complete function is shown below:

//2.0 Function with variable argument list
double Power_Summation(long No_Params, int RaiseTo, ...)
{
  va_list param_list;
  va_start(param_list, RaiseTo);
  double sum = 0;

  for (long i=0; i<No_Params; i++)
  {
	  double base = va_arg(param_list, double);
	  sum = sum + pow(base, RaiseTo);
  }
  va_end(param_list);
  return sum;
}

In the Main() function, you can see the variadic function Power_Summation is called twice. When it is called for the first time, three variadic float parameters 1.0, 2.0, 3.0 are passed-in. And in the second case, four variadic parameters are passed. The first two parameters are standard parameters, which convey a number of parameters, Raise to a power respectively. Below is main program entry:

//3.0 Calling the Function
void main()
{
	double Total;
	Total = Power_Summation(3, 2, 1.0f, 2.0f, 3.0f);
	printf("Result 1: %f\r\n", Total);

	Total = Power_Summation(4, 3, 2.0f, 1.0f, 2.0f, 3.0f);
	printf("Result 2: %f\r\n", Total);
}

Output of the above program is shown below:


Program Output - Variable Number of Arg.
Program Output - Variable Number of Arg. | Source

© 2015 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)