Variadic function: Difference between revisions

Content deleted Content added
: А а Б б В в Г г Ґ ґ Ѓ ѓ Д д Ђ ђ Е е Ё ё Є є Ж ж З з Ѕ ѕ И и І і Ї ї Й й Ј ј К к Ќ ќ Л л Љ љ М м Н н Њ њ О о П п Р р С с Т т Ћ ћ У у Ў ў Ф ф Х х Ц ц Ч ч Џ џ Ш ш Щ щ Ъ ъ Ы ы Ь ь Э э Ю ю Я я
Tags: Reverted Mobile edit Mobile web edit
Rescuing 1 sources and tagging 0 as dead.) #IABot (v2.0.9.5
 
(One intermediate revision by one other user not shown)
Line 20:
 
===In C===
To portably implement variadic functions in the [[C (programming language)|C language]], the standard [[stdarg.h|{{code|stdarg.h}}]] header file is used. The older [[varargs.h|{{code|varargs.h}}]] header has been [[Deprecation|deprecated]] in favor of {{code|stdarg.h}}. In C++, the header file {{code|cstdarg}} is used.<ref>{{cite web|url=http://www.cplusplus.com/reference/clibrary/cstdarg/|title=<cstdarg> (stdarg.h) - C++ Reference|website=www.cplusplus.com|access-date=2007-10-02|archive-date=2012-10-31|archive-url=https://web.archive.org/web/20121031160547/http://www.cplusplus.com/reference/clibrary/cstdarg/|url-status=dead}}</ref>
 
<syntaxhighlight lang="C">
Line 44:
return 0;
}
</syntaxhighlight>
 
 
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 {{code|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 {{code|NULL}} or {{code|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 {{code|NULL}} as a sentinel may encounter such problems; {{code|nullptr}} or a dedicated null pointer of the correct target type may be used to avoid them.