Variable Argument Lists CS 112 slides from Marc

Variable Argument Lists CS 112 (slides from Marc Lihan)

Definition n Also called Variadic function Methods containing parameter(s) that can accept different number of arguments Support for variadic functions differs among different programming languages n n C C# LISP PHP - C++ - Java - Visual Basic

C Programming Language n Most common variable argument functions are n n n void printf(const char* fmt, …); void scanf(const char* fmt, …); Parameters include n n One named argument usually a format string Ellipsis indicating the function may take any number of arguments and their types

Creating a Variadic Function n n Use standard header stdarg. h 4 macros (not prototypes) needed from this header file n n va_list va_start va_args va_end

Variable arguments in C n va_list n n Stores the list of arguments (argument pointer) Declared like any other variable Ex. va_list ap va_start n n initializes the list, point to the first argument Accepts two arguments n n n va_list Name of the variable that directly precedes the ellipsis Ex. va_start(ap, fmt)

Variable arguments in C n va_args n n n returns the next argument of whatever type it is told moves down to the next argument in the list Accepts two arguments n n va_list Variable argument type Ex. va_args(ap, int) //returns next int value in the argument va_end n n Cleans up the variable argument list Ex. va_end(ap)

C Sample Code #include <stdio. h> #include <stdarg. h> double average ( int num, . . . ) { va_list ap; double sum = 0; va_start ( ap, num ); //initializes, store all values int x; for ( x = 0; x < num; x++ ) sum += va_arg ( ap, double ); va_end ( ap ); return sum/num; } int main() { printf( "%fn", average ( 3, 12. 2, 22. 3, 4. 5 )); printf("%fn", average ( 5, 3. 3, 2. 2, 1. 1, 5. 5, 3. 3 )); return 0; }

C# n Variadic functions are also possible n n n Console. Write. Line (“Hi {0} and {1} nice to meet you. ”, “John”, “Marc” ); Output: Hi John and Marc nice to meet you. C# supports this behavior with the params keyword n public void sum(params int[] nums)
![Code Sample using System; class Total { static void Main(string[] args) { //call sum Code Sample using System; class Total { static void Main(string[] args) { //call sum](http://slidetodoc.com/presentation_image_h/80ede41547e1d051d6c911bcdefef3de/image-9.jpg)
Code Sample using System; class Total { static void Main(string[] args) { //call sum with no arguments, optional parameter Console. Write. Line( "Sum of the first problem is {0}", Sum()); //call with 5 arguments Console. Write. Line( "Sum of the second problem is {0}", Sum(3, 2, 6, 5, 9)); Console. Read. Line(); } public static int Sum(params int[] args) { int total = 0; Console. Write. Line("Number of arguments: " + args. Get. Length(0). To. String()); for (int i = 0; i<args. Get. Length(0); i++) total += args[i]; OUTPUT: return total; Number of arguments: 0 } Sum of the first problem is 0 } Number of arguments: 5 Sum of the second problem is 25

Java n n Newly implemented feature Java 5. 0 Basic syntax n n type … variable. Name Argument passed to a method is converted into an array of the sametyped values n sum (10, 20) sum(new int[] {10, 20})
![Sample Code public static void main(String[] args) { System. out. println(“The sum is ” Sample Code public static void main(String[] args) { System. out. println(“The sum is ”](http://slidetodoc.com/presentation_image_h/80ede41547e1d051d6c911bcdefef3de/image-11.jpg)
Sample Code public static void main(String[] args) { System. out. println(“The sum is ” + sum(10, 20, 30)); } public int sum (double … numbers) { int total = 0; for (int i = 0; i < numbers. length; i++) total += numbers[i]; OUTPUT: return total; The sum is 60 }

Formatting in Java 1. 5 n n Employs variable arguments printf() and format() method of Print. Stream and String n n n System. out. printf( “%5 d %6. 2 f”, 23, 45. 6 ); Formats data values of arbitrary data types and outputs the formatted results String s = String. format(“%. 2 f”, 1234. 567) n n “%. 2 f” round of to the nearest hundredths: 1234. 57 “%04 d” integer should be formatted with a minimum of 4 digits: 01234

Visual Basic n Parameter array allows a procedure to accept an array of values for an argument. n n Must be passed by value. Syntax n Sub Method. Name (By. Val Param. Array array() As String)

Sample Code Sub Sum(By. Val Param. Array Nums() As Integer) Dim I As Integer Dim Total As Integer For I = 0 To UBound(Nums) Total = Total + Nums(I) Next I Debug. Write. Line("The sum is " & Total & ". ") End Sub n Sum( 10, 26, 32, 15 ) n OUTPUT: The sum is 83.

Caveats n n No enforceable limit to the number of arguments without writing the code at runtime inside the function itself No way to make the array typesafe n n If multiple types are needed use the LCD approach, usually array as type Object Only one parameter may be marked using params or ellipsis It must be the last parameter The arguments are automatically optional, it can be one, many or none at all

Syntax Summary n C n n Java n n … method( type … var. Name ) C# n n … function_name( type first_arg, … ) … Method( params type num[] ) Visual Basic n Sub Method. Name(By. Val Param. Array array() As String)

PHP n Unlike other programming language, method signatures of PHP are purely for syntax checking n n n Will never complain if you call a function with more parameters than what's defined It will only complain if you call it with less Related methods in PHP n n n func_get_args(void) – returns an array comprising a function’s argument list func_num_args(void) – returns the total length of the array func_get_arg(int arg_num) – returns an item in the argument list

PHP Sample Code <? php function average() { $array = func_get_args(); $sum = array_sum($array); $num = func_num_args(); if ($num == 0) return 0; else return $sum/$num; } echo average(10, 15, 20); ? > § array_sum() – calculates the sum of the values in an array § OUTPUT: 15
- Slides: 18