190 likes | 394 Views
Variable Argument Lists. CS 112 (slides from Marc Lihan). Definition. Also called Variadic function Methods containing parameter(s) that can accept different number of arguments Support for variadic functions differs among different programming languages C - C++ C# - Java
E N D
Variable Argument Lists CS 112 (slides from Marc Lihan)
Definition • Also called Variadic function • Methods containing parameter(s) that can accept different number of arguments • Support for variadic functions differs among different programming languages • C - C++ • C# - Java • LISP - Visual Basic • PHP
C Programming Language • Most common variable argument functions are • void printf(const char* fmt, …); • void scanf(const char* fmt, …); • Parameters include • One named argument usually a format string • Ellipsis indicating the function may take any number of arguments and their types
Creating a Variadic Function • Use standard header stdarg.h • 4 macros (not prototypes) needed from this header file • va_list • va_start • va_args • va_end
Variable arguments in C • va_list • Stores the list of arguments (argument pointer) • Declared like any other variable • Ex. va_list ap • va_start • initializes the list, point to the first argument • Accepts two arguments • va_list • Name of the variable that directly precedes the ellipsis • Ex. va_start(ap, fmt)
Variable arguments in C • va_args • returns the next argument of whatever type it is told • moves down to the next argument in the list • Accepts two arguments • va_list • Variable argument type • Ex. va_args(ap, int) //returns next int value in the argument • va_end • 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( "%f\n", average ( 3, 12.2, 22.3, 4.5 )); printf("%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 )); return 0; }
C# • Variadic functions are also possible • Console.WriteLine(“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 • public void sum(params int[] nums)
Code Sample using System; class Total { static void Main(string[] args) { //call sum with no arguments, optional parameter Console.WriteLine( "Sum of the first problem is {0}", Sum()); //call with 5 arguments Console.WriteLine( "Sum of the second problem is {0}", Sum(3,2,6,5,9)); Console.ReadLine(); } public static int Sum(params int[] args) { int total = 0; Console.WriteLine("Number of arguments: " + args.GetLength(0).ToString()); for (int i = 0; i<args.GetLength(0); i++) total += args[i]; return total; } } OUTPUT: Number of arguments: 0 Sum of the first problem is 0 Number of arguments: 5 Sum of the second problem is 25
Java • Newly implemented feature Java 5.0 • Basic syntax • type … variableName • Argument passed to a method is converted into an array of the same-typed values • sum (10,20) sum(new int[] {10,20})
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]; return total; } OUTPUT:The sum is 60
Formatting in Java 1.5 • Employs variable arguments • printf() and format() method of PrintStream and String • System.out.printf( “%5d %6.2f”, 23, 45.6 ); • Formats data values of arbitrary data types and outputs the formatted results • String s = String.format(“%.2f”, 1234.567) • “%.2f” round of to the nearest hundredths: 1234.57 • “%04d” integer should be formatted with a minimum of 4 digits: 01234
Visual Basic • Parameter array allows a procedure to accept an array of values for an argument. • Must be passed by value. • Syntax • Sub MethodName(ByVal ParamArray array() As String)
Sample Code Sub Sum(ByVal ParamArray Nums() As Integer) Dim I As Integer Dim Total As Integer For I = 0 To UBound(Nums) Total = Total + Nums(I) Next I Debug.WriteLine("The sum is " & Total & ".") End Sub • Sum( 10, 26, 32, 15 ) • OUTPUT: The sum is 83.
Caveats • 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 • 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 • C • … function_name( type first_arg, … ) • Java • … method( type … varName ) • C# • … Method( params type num[] ) • Visual Basic • Sub MethodName(ByVal ParamArray array() As String)
PHP • Unlike other programming language, method signatures of PHP are purely for syntax checking • 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 • 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