官术网_书友最值得收藏!

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

主站蜘蛛池模板: 凌海市| 兴隆县| 河北区| 日喀则市| 瑞丽市| 万宁市| 和平县| 阿尔山市| 成武县| 偃师市| 抚松县| 云南省| 内黄县| 韩城市| 淄博市| 克什克腾旗| 五家渠市| 新津县| 东丰县| 瑞丽市| 扎赉特旗| 永川市| 邢台市| 乐至县| 固阳县| 来凤县| 山阳县| 青阳县| 大足县| 会宁县| 铜鼓县| 黄冈市| 周至县| 墨玉县| 阿瓦提县| 新绛县| 余姚市| 都匀市| 中卫市| 白银市| 乡城县|