- C++ Fundamentals
- Antonio Mallia Francesco Zoffoli
- 228字
- 2021-06-11 13:36:00
Default Arguments
Another feature C++ provides to make life easier for the caller when it comes to calling functions are default arguments.
Default arguments are added to a function declaration. The syntax is to add an = sign and supply the value of the default argument after the identifier of the parameter of the function. An example of this would be:
int multiply(int multiplied, int multiplier = 1);
The caller of the function can call multiply either with 1 or 2 arguments:
multiply(10); // Returns 10
multiply(10, 2); // Returns 20
When an argument with a default value is omitted, the function uses the default value instead. This is extremely convenient if there are functions with sensible defaults that callers mostly do not want to modify, except in specific cases.
Imagine a function that returns the first word of a string:
char const * firstWord(char const * string, char separator = ' ').
Most of the time, a word is separated by a whitespace character, but a function can decide whether or not it should use a different separator. The fact that a function offers the possibility to provide a separator is not forcing most callers, which simply want to use the space, to specify it.
It is a best practice to set the default arguments in the function signature declaration, and not declare them in the definition.
- Python概率統(tǒng)計(jì)
- JavaScript全程指南
- Mastering JavaScript Object-Oriented Programming
- Visual Basic編程:從基礎(chǔ)到實(shí)踐(第2版)
- PyTorch自然語言處理入門與實(shí)戰(zhàn)
- HTML5+CSS3基礎(chǔ)開發(fā)教程(第2版)
- C++寶典
- App Inventor創(chuàng)意趣味編程進(jìn)階
- INSTANT Yii 1.1 Application Development Starter
- 深度學(xué)習(xí)原理與PyTorch實(shí)戰(zhàn)(第2版)
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)指導(dǎo)
- Python Projects for Kids
- 零基礎(chǔ)學(xué)C++(升級(jí)版)
- jQuery從入門到精通(微課精編版)
- 深度學(xué)習(xí)入門:基于Python的理論與實(shí)現(xiàn)