临界心电图是什么意思| 云南什么族| 飧泄是什么意思| 醋酸是什么| 砂舞是什么意思| 劼字取名的寓意是什么| 胃溃疡a1期是什么意思| 欧洲为什么没有统一| 私是什么意思| 过意不去是什么意思| 夏季喝什么茶好| 缺钙会导致什么| 嗓子痒咳嗽吃什么药| 感冒了吃什么药| 丝瓜配什么炒好吃| 钠低是什么原因造成的| mps是什么意思| 上海松江有什么好玩的地方| 长期服用丙戊酸钠有什么副作用| 四叶草项链是什么牌子| 人活一辈子到底为了什么| 下面有异味用什么药| 十岁女孩喜欢什么礼物| 血小板分布宽度偏低是什么原因| 左手大拇指麻木是什么原因| 02年的马是什么命| 梦见自己的哥哥死了是什么意思| ih是什么意思| 消瘦是什么意思| 菊花什么颜色| 牛头马面是什么生肖| 4月2号是什么星座| 什么的身体| 经期有血块是什么原因| 宫寒吃什么| 什么是庚日| 哪吒的武器是什么| 萎缩性胃炎是什么原因引起的| ahc是韩国什么档次| 还记得年少时的梦吗是什么歌| 睡鼠吃什么| 纳米是什么单位| 扁平化管理是什么意思| 华西医院院长什么级别| 头部ct能检查出什么| 鸡蛋壳属于什么垃圾| 什么药去湿气最好最快| 毛宁和毛阿敏是什么关系| 西红柿不能跟什么一起吃| 口腔溃疡吃什么维生素| 常字五行属什么| 厨房墙砖什么颜色好看| 凉皮加什么才柔软筋道| 翩翩起舞是什么意思| 嘴辰发紫是什么病| 慢性胆囊炎是什么原因引起的| 权衡利弊是什么意思| 尿隐血是什么原因引起的| 仕女图是什么意思| 流鼻血是什么引起的| 他说风雨中这点痛算什么| 无非是什么意思| 嘴苦是什么原因引起的| 牡丹是什么季节开的| 七月与安生讲的是什么| 梦见洗手是什么意思| 小儿发烧吃什么食物好| 医院门特是什么意思| 条子是什么意思| 77年属蛇的是什么命| 多吃鱼有什么好处| 特需门诊和专家门诊有什么区别| 陈醋和香醋有什么区别| 达英35是什么药| 什么昆虫最值钱| hcg值是什么| 一什么露珠| 广州的市花是什么| 外阴瘙痒什么原因引起| 肺结节吃什么中成药| 牙冠是什么样子的图片| 一个合一个页读什么| 风口浪尖是什么意思| 拔罐之后要注意什么| 肉燕是什么做的| 核糖体由什么组成| 止吐针是什么药| 梦见手机失而复得是什么意思| 玉女心经是什么意思| 海石花是什么| 苟同什么意思| 小s和黄子佼为什么分手| 2001年是什么年| 婚检能检查出什么| 男人眉毛短是什么面相| 怀孕16周要做什么检查| 蒲公英和什么一起泡水喝最好| 李倩梅结局是什么| 喇叭裤配什么鞋子好看| 为什么姓张的不用说免贵| 周易和易经有什么区别| 唐朝灭亡后是什么朝代| 拔智齿后可以吃什么| 马桶堵了用什么疏通| 什么是碳水| 戒奶涨奶痛有什么缓解方法| 特殊情况是什么意思| 丁胺卡那又叫什么药名| 7月29日什么星座| 景五行属什么| 什么是大小周| 性欲什么意思| human是什么意思| 草莽是什么意思| 梵高的星空表达了什么| 慢性胰腺炎有什么症状| 麻古是什么| 和衣是什么意思| 524是什么意思| 福寿螺为什么不能吃| 亢奋是什么意思| 4月21日什么星座| 什么是辛辣刺激性食物| 一什么无余| 叶酸片什么时候吃最好| 细菌性痢疾症状是什么| 壬是什么意思| 里急后重吃什么药最好| hpv什么病毒| lt是什么意思| 心脏呈逆钟向转位什么意思| 膝盖响是什么原因| 天蝎座和什么星座不合| 为什么不建议年轻人做肠镜| 0n是什么意思| 饧是什么意思| 胆结石吃什么水果好| 白癜风用什么药| 黑芝麻和白芝麻有什么区别| 梦见自己得了绝症预示着什么| 天秤座什么象| 导管是什么意思| 表面活性剂是什么| 双重性格是什么意思| 怀二胎初期有什么症状| 什么样的花| 出家需要什么条件| 白细胞高吃什么降得快| 叶酸片治什么病| 什么是三重一大事项| 4月28日什么星座| 芳心是什么意思| 尿的正常颜色是什么样| 气血两虚是什么意思| 西洋参有什么作用和功效| 男生为什么要做包皮手术| 高密度脂蛋白胆固醇是什么意思| 全品类是什么意思| 化疗后吃什么恢复快| 以免是什么意思| 高血压吃什么降的快| 偶尔头晕是什么原因| 头顶痛吃什么药效果好| 刮宫是什么| 坐围和臀围有什么区别| 偏头疼挂什么科室| 美甲光疗是什么| 中性粒细胞偏高是什么意思| 牙齿痛吃什么药最管用| 内痔是什么样的图片| 吃什么去黄褐斑最有效| 身体潮湿是什么原因| 肾小球滤过率偏高说明什么| 蓝色药片是什么药| 在什么上面| 吃什么不长肉还能瘦| 总胆红素偏高是什么原因| 临界点是什么意思| 亢进是什么意思| 做完无痛人流需要注意什么| 解脲脲原体阳性是什么| c反应蛋白是什么| 肚子疼发烧是什么病症| 吃什么才能提高免疫力| 电子邮件地址是什么意思| 红苕是什么| 平面模特是做什么的| 欢什么喜什么| 电视剧上星是什么意思| 身在其位必谋其职是什么意思| 高密度脂蛋白偏低是什么意思| 喉咙肿痛吃什么药好| 深圳市长什么级别| 槟榔为什么那么贵| 什么牌助听器好| c罗全名叫什么| 嗓子疼吃什么水果好得快| 一什么凤冠| 腹部叩诊什么音正常| 当兵有什么好处| 回应是什么意思| 送镜子代表什么意思| 塔罗是什么| 脑膜炎是什么| 啄木鸟为什么不会脑震荡| 一月二十五号是什么星座| 米肉是什么| 身上肉疼是什么原因| 吃什么排黑色素最强| 老婆饼为什么叫老婆饼| 灵官爷是什么神| 九月初四是什么星座| 尿频尿急吃什么药比较好| 梦到男朋友出轨了预示什么意思| 眼霜有什么作用和功效| 青海古代叫什么| 胃消化不良吃什么药| 放行是什么意思| 微信什么时候开始的| ra是什么| 汉朝后面是什么朝代| 梦见很多人是什么意思| 信阳毛尖属于什么茶| 山宗读什么| 黄精和什么泡水喝最好| 为什么夏天容易拉肚子| 京酱肉丝用什么酱| 手机飞行模式是什么意思| 一个小时尿一次是什么原因| 双性是什么意思| 喉咙痛有痰吃什么药| 风湿性关节炎什么症状| 女孩子学什么专业好| 看甲状腺挂什么科| 什么笑什么笑| 什么是亲情| 关帝是什么神| 尖锐湿疣用什么药| 吃什么补大脑记忆力| 胃疼做什么检查| ttl什么意思| 牙龈溃烂是什么原因| 儿童红眼病用什么眼药水| 眼睑痉挛是什么原因造成的| 胃疼做什么检查| 疯子是什么意思| 结节性红斑吃什么药| 腹胀是什么原因引起的| 青筋明显是什么原因| 南京区委书记什么级别| 一什么树| m1是什么单位| 小暑吃什么| 吐黄痰是什么原因| 什么样的季节| 两个人可以玩什么| 白干是什么| 绰号是什么意思| 1988属什么| 来姨妈不能吃什么水果| 褥疮是什么| 有什么蔬菜| 左撇子是什么意思| 尿隐血阳性什么意思| 百度

云南普洱现"会走路的树叶" 专家为珍稀竹节虫

(Redirected from Variadic functions)
百度 袁复礼痛感祖国被“弱肉强食”,竭力劝学生学地质。

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

The term variadic is a neologism, dating back to 1936/1937.[1] The term was not widely used until the 1970s.

Overview

edit

There are many mathematical and logical operations that come across naturally as variadic functions. For instance, the summing of numbers or the concatenation of strings or other sequences are operations that can be thought of as applicable to any number of operands (even though formally in these cases the associative property is applied).

Another operation that has been implemented as a variadic function in many languages is output formatting. The C function printf and the Common Lisp function format are two such examples. Both take one argument that specifies the formatting of the output, and any number of arguments that provide the values to be formatted.

Variadic functions can expose type-safety problems in some languages. For instance, C's printf, if used incautiously, can give rise to a class of security holes known as format string attacks. The attack is possible because the language support for variadic functions is not type-safe: it permits the function to attempt to pop more arguments off the stack than were placed there, corrupting the stack and leading to unexpected behavior. As a consequence of this, the CERT Coordination Center considers variadic functions in C to be a high-severity security risk.[2]

In functional programming languages, variadics can be considered complementary to the apply function, which takes a function and a list/sequence/array as arguments, and calls the function with the arguments supplied in that list, thus passing a variable number of arguments to the function.[citation needed] In the functional language Haskell, variadic functions can be implemented by returning a value of a type class T; if instances of T are a final return value r and a function (T t) => x -> t, this allows for any number of additional arguments x.[further explanation needed]

A related subject in term rewriting research is called hedges, or hedge variables.[3] Unlike variadics, which are functions with arguments, hedges are sequences of arguments themselves. They also can have constraints ('take no more than 4 arguments', for example) to the point where they are not variable-length (such as 'take exactly 4 arguments') - thus calling them variadics can be misleading. However they are referring to the same phenomenon, and sometimes the phrasing is mixed, resulting in names such as variadic variable (synonymous to hedge). Note the double meaning of the word variable and the difference between arguments and variables in functional programming and term rewriting. For example, a term (function) can have three variables, one of them a hedge, thus allowing the term to take three or more arguments (or two or more if the hedge is allowed to be empty).

Examples

edit

In C

edit

To portably implement variadic functions in the C language, the standard stdarg.h header file is used. The older varargs.h header has been deprecated in favor of stdarg.h. In C++, the header file cstdarg is used.[4]

#include <stdarg.h>
#include <stdio.h>

double average(int count, ...) {
    va_list ap;
    int j;
    double sum = 0;

    va_start(ap, count); /* Before C23: Requires the last fixed parameter (to get the address) */
    for (j = 0; j < count; j++) {
        sum += va_arg(ap, int); /* Increments ap to the next argument. */
    }
    va_end(ap);

    return sum / count;
}

int main(int argc, char const *argv[]) {
    printf("%f\n", average(3, 1, 2, 3));
    return 0;
}

This will compute the average of an arbitrary number of arguments. Note that the function does not know the number of arguments or their types. The above function expects that the types will be int, and that the number of arguments is passed in the first argument (this is a frequent usage but by no means enforced by the language or compiler). In some other cases, for example printf, the number and types of arguments are figured out from a format string. In both cases, this depends on the programmer to supply the correct information. (Alternatively, a sentinel value like NULL or nullptr may be used to indicate the end of the parameter list.) If fewer arguments are passed in than the function believes, or the types of arguments are incorrect, this could cause it to read into invalid areas of memory and can lead to vulnerabilities like the format string attack. Depending on the system, even using NULL as a sentinel may encounter such problems; nullptr or a dedicated null pointer of the correct target type may be used to avoid them.

stdarg.h declares a type, va_list, and defines four macros: va_start, va_arg, va_copy, and va_end. Each invocation of va_start and va_copy must be matched by a corresponding invocation of va_end. When working with variable arguments, a function normally declares a variable of type va_list (ap in the example) that will be manipulated by the macros.

  1. va_start takes two arguments, a va_list object and a reference to the function's last parameter (the one before the ellipsis; the macro uses this to get its bearings). In C23, the second argument will no longer be required and variadic functions will no longer need a named parameter before the ellipsis.[note 1][6] It initialises the va_list object for use by va_arg or va_copy. The compiler will normally issue a warning if the reference is incorrect (e.g. a reference to a different parameter than the last one, or a reference to a wholly different object), but will not prevent compilation from completing normally.
  2. va_arg takes two arguments, a va_list object (previously initialised) and a type descriptor. It expands to the next variable argument, and has the specified type. Successive invocations of va_arg allow processing each of the variable arguments in turn. Unspecified behavior occurs if the type is incorrect or there is no next variable argument.
  3. va_end takes one argument, a va_list object. It serves to clean up. If one wanted to, for instance, scan the variable arguments more than once, the programmer would re-initialise your va_list object by invoking va_end and then va_start again on it.
  4. va_copy takes two arguments, both of them va_list objects. It clones the second (which must have been initialised) into the first. Going back to the "scan the variable arguments more than once" example, this could be achieved by invoking va_start on a first va_list, then using va_copy to clone it into a second va_list. After scanning the variable arguments a first time with va_arg and the first va_list (disposing of it with va_end), the programmer could scan the variable arguments a second time with va_arg and the second va_list. va_end needs to also be called on the cloned va_list before the containing function returns.

In C#

edit

C# describes variadic functions using the params keyword. A type must be provided for the arguments, although object[] can be used as a catch-all. At the calling site, you can either list the arguments one by one, or hand over a pre-existing array having the required element type. Using the variadic form is Syntactic sugar for the latter.

using System;

class Program
{
    static int Foo(int a, int b, params int[] args)
    {
        // Return the sum of the integers in args, ignoring a and b.
        int sum = 0;
        foreach (int i in args)
            sum += i;
        return sum;
    }
        
    static void Main(string[] args)
    {
        Console.WriteLine(Foo(1, 2));  // 0
        Console.WriteLine(Foo(1, 2, 3, 10, 20));  // 33
        int[] manyValues = new int[] { 13, 14, 15 };
        Console.WriteLine(Foo(1, 2, manyValues));  // 42
    }
}

In C++

edit

The basic variadic facility in C++ is largely identical to that in C. The only difference is in the syntax, where the comma before the ellipsis can be omitted. C++ allows variadic functions without named parameters but provides no way to access those arguments since va_start requires the name of the last fixed argument of the function.

#include <iostream>
#include <cstdarg>

void simple_printf(const char* fmt...)      // C-style "const char* fmt, ..." is also valid
{
    va_list args;
    va_start(args, fmt);
 
    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            std::cout << i << '\n';
        } else if (*fmt == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            std::cout << static_cast<char>(c) << '\n';
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            std::cout << d << '\n';
        }
        ++fmt;
    }
 
    va_end(args);
}

int main()
{
    simple_printf("dcff", 3, 'a', 1.999, 42.5); 
}

Variadic templates (parameter pack) can also be used in C++ with language built-in fold expressions.

#include <iostream>

template <typename... Ts>
void foo_print(Ts... args) 
{
    ((std::cout << args << ' '), ...);
}

int main()
{
    std::cout << std::boolalpha;
    foo_print(1, 3.14f); // 1 3.14
    foo_print("Foo", 'b', true, nullptr); // Foo b true nullptr
}

The CERT Coding Standards for C++ strongly prefers the use of variadic templates (parameter pack) in C++ over the C-style variadic function due to a lower risk of misuse.[7]

In Fortran

edit

Since the Fortran 90 revision, Fortran functions or subroutines can accept optional arguments:[8] the argument list is still fixed, but the ones that have the optional attribute can be omitted in the function/subroutine call. The intrinsic function present() can be used to detect the presence of an optional argument. The optional arguments can appear anywhere in the argument list.

program test
implicit none

    real :: x
    
    !> all arguments are passed:
    call foo( 1, 2, 3.0, 4, x )
    !< outputs 1 \ 2 \ 3.0 \ 4 \ 6.0 (the "\" denotes a newline)
    
    !> the last 2 arguments are omitted:
    call foo( 1, 2, 3.0 )
    !< outputs 1 \ 2 \ 3.0
    
    !> the 2nd and 4th arguments are omitted: the arguments that are positioned after 
    !> an omitted argument must be passed with a keyword:
    call foo( 1, c=3.0, e=x ) 
    !< outputs 1 \ 3.0 \ 6.0
    
    !> alternatively, the Fortran 2023 revision has introduced the .NIL. pseudo constant
    !> to denote an omitted argument
    call foo( 1, .NIL., 3.0, .NIL., x )
    !< outputs 1 \ 3.0 \ 6.0

contains

    !> the subroutine foo() has 2 mandatory and 3 optional arguments
    subroutine foo( a, b, c, d, e )
        integer, intent(in)            :: a 
        integer, intent(in),  optional :: b
        real,    intent(in)            :: c
        integer, intent(in),  optional :: d
        real,    intent(out), optional :: e
        
        print*, a
        if (present(b)) print*, b 
        print*, c
        if (present(d)) print*, d
        if (present(e)) then
            e = 2*c
            print*, c
        end if
    end subroutine

end program

Output:

The sum of [1 2] is 3 
The sum of [1 2 3] is 6 
The sum of [1 2 3 4] is 10

In Go

edit

Variadic functions in Go can be called with any number of trailing arguments.[9] fmt.Println is a common variadic function; it uses an empty interface as a catch-all type.

package main

import "fmt"

// This variadic function takes an arbitrary number of ints as arguments.
func sum(nums ...int) {
	fmt.Print("The sum of ", nums) // Also a variadic function.
	total := 0
	for _, num := range nums {
		total += num
	}
	fmt.Println(" is", total) // Also a variadic function.
}

func main() {
	// Variadic functions can be called in the usual way with individual
	// arguments.
	sum(1, 2)  // "The sum of [1 2] is 3"
	sum(1, 2, 3) // "The sum of [1 2 3] is 6"

	// If you already have multiple args in a slice, apply them to a variadic
	// function using func(slice...) like this.
	nums := []int{1, 2, 3, 4}
	sum(nums...) // "The sum of [1 2 3 4] is 10"
}

Output:

The sum of [1 2] is 3 
The sum of [1 2 3] is 6 
The sum of [1 2 3 4] is 10

In Java

edit

As with C#, the Object type in Java is available as a catch-all.

public class Program {
    // Variadic methods store any additional arguments they receive in an array.
    // Consequentially, `printArgs` is actually a method with one parameter: a
    // variable-length array of `String`s.
    private static void printArgs(String... strings) {
        for (String string : strings) {
            System.out.println(string);
        }
    }

    public static void main(String[] args) {
        printArgs("hello");          // short for printArgs(["hello"])
        printArgs("hello", "world"); // short for printArgs(["hello", "world"])
    }
}

In JavaScript

edit

JavaScript does not care about types of variadic arguments.

function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(3, 2));    // 5
console.log(sum());        // 0

It's also possible to create a variadic function using the arguments object, although it is only usable with functions created with the function keyword.

function sum() {
    return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(3, 2));    // 5
console.log(sum());        // 0

Lua functions may pass varargs to other functions the same way as other values using the return keyword. tables can be passed into variadic functions by using, in Lua version 5.2 or higher[10] table.unpack, or Lua 5.1 or lower[11] unpack. Varargs can be used as a table by constructing a table with the vararg as a value.

function sum(...) --... designates varargs
   local sum=0
   for _,v in pairs({...}) do --creating a table with a varargs is the same as creating one with standard values
      sum=sum+v
   end
   return sum
end

values={1,2,3,4}
sum(5,table.unpack(values)) --returns 15. table.unpack should go after any other arguments, otherwise not all values will be passed into the function.

function add5(...)
  return ...+5 --this is incorrect usage of varargs, and will only return the first value provided
end

entries={}
function process_entries()
   local processed={}
   for i,v in pairs(entries) do
      processed[i]=v --placeholder processing code
   end
   return table.unpack(processed) --returns all entries in a way that can be used as a vararg
end

print(process_entries()) --the print function takes all varargs and writes them to stdout separated by newlines

In Pascal

edit

Pascal is standardized by ISO standards 7185 (“Standard Pascal”) and 10206 (“Extended Pascal”). Neither standardized form of Pascal supports variadic routines, except for certain built-in routines (read/readLn and write/writeLn, and additionally in EP readStr/writeStr).

Nonetheless, dialects of Pascal implement mechanisms resembling variadic routines. Delphi defines an array of const data type that may be associated with the last formal parameter. Within the routine definition the array of const is an array of TVarRec, an array of variant records.[12] The VType member of the aforementioned record data type allows inspection of the argument’s data type and subsequent appropriate handling. The Free Pascal Compiler supports Delphi’s variadic routines, too.[13]

This implementation, however, technically requires a single argument, that is an array. Pascal imposes the restriction that arrays need to be homogenous. This requirement is circumvented by utilizing a variant record. The GNU Pascal defines a real variadic formal parameter specification using an ellipsis (...), but as of 2022 no portable mechanism to use such has been defined.[14]

Both GNU Pascal and FreePascal allow externally declared functions to use a variadic formal parameter specification using an ellipsis (...).

In PHP

edit

PHP does not care about types of variadic arguments unless the argument is typed.

function sum(...$nums): int
{
    return array_sum($nums);
}

echo sum(1, 2, 3); // 6

And typed variadic arguments:

function sum(int ...$nums): int
{
    return array_sum($nums);
}

echo sum(1, 'a', 3); // TypeError: Argument 2 passed to sum() must be of the type int (since PHP 7.3)

In Python

edit

Python does not care about types of variadic arguments.

def foo(a, b, *args):
    print(args)  # args is a tuple (immutable sequence).

foo(1, 2) # ()
foo(1, 2, 3) # (3,)
foo(1, 2, 3, "hello") # (3, "hello")

Keyword arguments can be stored in a dictionary, e.g. def bar(*args, **kwargs).

In Raku

edit

In Raku, the type of parameters that create variadic functions are known as slurpy array parameters and they're classified into three groups:

Flattened slurpy

edit

These parameters are declared with a single asterisk (*) and they flatten arguments by dissolving one or more layers of elements that can be iterated over (i.e, Iterables).

sub foo($a, $b, *@args) {
    say @args.perl;
}

foo(1, 2)                  # []
foo(1, 2, 3)               # [3]
foo(1, 2, 3, "hello")      # [3 "hello"]
foo(1, 2, 3, [4, 5], [6]); # [3, 4, 5, 6]

Unflattened slurpy

edit

These parameters are declared with two asterisks (**) and they do not flatten any iterable arguments within the list, but keep the arguments more or less as-is:

sub bar($a, $b, **@args) {
    say @args.perl;
}

bar(1, 2);                 # []
bar(1, 2, 3);              # [3]
bar(1, 2, 3, "hello");     # [3 "hello"]
bar(1, 2, 3, [4, 5], [6]); # [3, [4, 5], [6]]

Contextual slurpy

edit

These parameters are declared with a plus (+) sign and they apply the "single argument rule", which decides how to handle the slurpy argument based upon context. Simply put, if only a single argument is passed and that argument is iterable, that argument is used to fill the slurpy parameter array. In any other case, +@ works like **@ (i.e., unflattened slurpy).

sub zaz($a, $b, +@args) {
    say @args.perl;
}

zaz(1, 2);                 # []
zaz(1, 2, 3);              # [3]
zaz(1, 2, 3, "hello");     # [3 "hello"]
zaz(1, 2, [4, 5]);         # [4, 5], single argument fills up array
zaz(1, 2, 3, [4, 5]);      # [3, [4, 5]], behaving as **@
zaz(1, 2, 3, [4, 5], [6]); # [3, [4, 5], [6]], behaving as **@

In Ruby

edit

Ruby does not care about types of variadic arguments.

def foo(*args)
  print args
end

foo(1)
# prints `[1]=> nil`

foo(1, 2)
# prints `[1, 2]=> nil`

In Rust

edit

Rust does not support variadic arguments in functions. Instead, it uses macros.[15]

macro_rules! calculate {
    // The pattern for a single `eval`
    (eval $e:expr) => {{
        {
            let val: usize = $e; // Force types to be integers
            println!("{} = {}", stringify!{$e}, val);
        }
    }};

    // Decompose multiple `eval`s recursively
    (eval $e:expr, $(eval $es:expr),+) => {{
        calculate! { eval $e }
        calculate! { $(eval $es),+ }
    }};
}

fn main() {
    calculate! { // Look ma! Variadic `calculate!`!
        eval 1 + 2,
        eval 3 + 4,
        eval (2 * 3) + 1
    }
}

Rust is able to interact with C's variadic system via a c_variadic feature switch. As with other C interfaces, the system is considered unsafe to Rust.[16]

In Scala

edit
object Program {
  // Variadic methods store any additional arguments they receive in an array.
  // Consequentially, `printArgs` is actually a method with one parameter: a
  // variable-length array of `String`s.
  private def printArgs(strings: String*): Unit = {
    strings.foreach(println)
  }

  def main(args: Array[String]): Unit = {
    printArgs("hello");          // short for printArgs(["hello"])
    printArgs("hello", "world"); // short for printArgs(["hello", "world"])
  }
}

In Swift

edit

Swift cares about the type of variadic arguments, but the catch-all Any type is available.

func greet(timeOfTheDay: String, names: String...) {
    // here, names is [String]
    
    print("Looks like we have \(names.count) people")
    
    for name in names {
        print("Hello \(name), good \(timeOfTheDay)")
    }
}

greet(timeOfTheDay: "morning", names: "Joseph", "Clara", "William", "Maria")

// Output:
// Looks like we have 4 people
// Hello Joseph, good morning
// Hello Clara, good morning
// Hello William, good morning
// Hello Maria, good morning

In Tcl

edit

A Tcl procedure or lambda is variadic when its last argument is args: this will contain a list (possibly empty) of all the remaining arguments. This pattern is common in many other procedure-like methods.[17][18]

proc greet {timeOfTheDay args} {
    puts "Looks like we have [llength $args] people"

    foreach name $args {
        puts "Hello $name, good $timeOfTheDay"
    }
}

greet "morning" "Joseph" "Clara" "William" "Maria"

# Output:
# Looks like we have 4 people
# Hello Joseph, good morning
# Hello Clara, good morning
# Hello William, good morning
# Hello Maria, good morning

See also

edit

Notes

edit
  1. ^ Making the named parameter optional was needed since there was no way to specify a function taking an unspecified number of arguments in C23 after the removal of K&R style function definitions. Since C++ was already using this syntax for the same purpose, this change was also a way to increase compatibility between the languages.[5]

References

edit
  1. ^ Henry S. Leonard and H. N. Goodman, A calculus of individuals. Abstract of a talk given at the Second Meeting of the Association for Symbolic Logic, held in Cambridge MA on December 28–30, 1936, [1], Journal of Symbolic Logic 2(1) 1937, 63.
  2. ^ Klemens, Ben (2014). 21st Century C: C Tips from the New School. O'Reilly Media, Inc. p. 224. ISBN 978-1491904442.
  3. ^ CLP (H): Constraint Logic Programming for Hedges
  4. ^ "<cstdarg> (stdarg.h) - C++ Reference". www.cplusplus.com. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  5. ^ "C23 is Finished: Here is What is on the Menu §N2975 - Relax requirements for variadic parameter lists". 31 July 2022.
  6. ^ Gilding, Alex; Meneide, JeanHeyd (2025-08-07). "WG14-N2975 : Relax requirements for variadic parameter lists, v3" (PDF).
  7. ^ "DCL50-CPP. Do not define a C-style variadic function".
  8. ^ "Optional Arguments". Intel. Retrieved 2025-08-07.
  9. ^ "Go by Example: Variadic Functions".
  10. ^ "Lua 5.2 Reference Manual". www.lua.org. Retrieved 2025-08-07.
  11. ^ "Lua 5.1 Reference Manual". www.lua.org. Retrieved 2025-08-07.
  12. ^ "Parameters (Delphi)". Retrieved 2025-08-07.
  13. ^ "Free Pascal - Reference guide". Retrieved 2025-08-07.
  14. ^ "The GNU Pascal Manual". Retrieved 2025-08-07.
  15. ^ "Variadics". Rust By Example.
  16. ^ "2137-variadic". The Rust RFC Book.
  17. ^ "proc manual page". Tcl/Tk Documentation.
  18. ^ "args". Tcler's Wiki.
edit
前列腺增大伴钙化灶是什么意思 故什么意思 女人梦见蛇预示着什么 中筋面粉是什么粉 盆腔积液是什么原因
咳嗽无痰吃什么药 皮肤发痒用什么药 梦见明星是什么预兆 什么笑什么笑 倪字五行属什么
见血是什么兆头 支气管舒张试验阳性是什么意思 医学hr是什么意思 什么叫修辞手法 以色列人说什么语言
血小板为什么会高 k9什么意思 做肠镜要挂什么科 做蹲起有什么好处 海参是补什么的
角膜炎用什么眼药水xinmaowt.com 五十路是什么意思hcv7jop7ns1r.cn 脚癣用什么药最好hcv7jop7ns3r.cn 大修基金什么时候缴纳hcv7jop9ns7r.cn 胆红素高是什么原因引起的hcv8jop2ns2r.cn
打摆子是什么病hcv9jop2ns8r.cn 愿闻其详是什么意思hcv9jop5ns8r.cn 墨迹是什么意思hcv7jop7ns4r.cn 两个方一个土是什么字xinmaowt.com 肩膀疼应该挂什么科0735v.com
angelababy英文什么意思hcv9jop4ns0r.cn 郭五行属什么hcv7jop6ns6r.cn 坤字五行属什么hcv9jop2ns3r.cn 呆小症是缺乏什么激素hcv8jop5ns1r.cn 用鸡蛋滚脸有什么好处hcv8jop9ns9r.cn
什么是纤维化xianpinbao.com 后脑勺白头发多是什么原因hcv8jop6ns4r.cn 老本行是什么意思hcv9jop5ns1r.cn 什么原因得湿疹hcv7jop9ns0r.cn 头顶痛吃什么药效果好hcv8jop9ns9r.cn
百度