1 / 18

Variable Argument Lists

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

leigh
Download Presentation

Variable Argument Lists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Variable Argument Lists CS 112 (slides from Marc Lihan)

  2. 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

  3. 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

  4. 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

  5. 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)

  6. 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)

  7. 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; }

  8. 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)

  9. 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

  10. 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})

  11. 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

  12. 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

  13. 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)

  14. 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.

  15. 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

  16. 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)

  17. 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

  18. 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

More Related