Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Variadic function
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===In C++=== 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 parameter]]s but provides no way to access those arguments since <code>va_start</code> requires the name of the last fixed argument of the function. <!-- When C23 is released the text should be updated to reflect that this is a difference between the languages. When C++26 ports the one argument va_start to C++ (https://wg21.link/p2537) this should be updated again. See also the C section of the article. --> <syntaxhighlight lang="c++"> #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); } </syntaxhighlight> [[Variadic templates]] (parameter pack) can also be used in C++ with language built-in [[Fold (higher-order function)|fold expressions]]. <syntaxhighlight lang="c++"> #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 } </syntaxhighlight> 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.<ref>{{cite web |title=DCL50-CPP. Do not define a C-style variadic function |url=https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL50-CPP}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)