Home >Backend Development >C++ >How do Default Parameter Values Work in C Functions?
Function Parameter Default Values
In C , functions can have default parameter values. This allows a function to be called with fewer arguments, with the default value being used for the missing argument.
When defining a function with a default parameter, the syntax is as follows:
<code class="cpp"><return-type> <function-name>(<arg-type1> <arg-name1>, <arg-type2> <arg-name2> = <default-value>);</code>
There are two ways to define a function with a default parameter:
Prototyping the function first:
<code class="cpp">int Add(int a, int b); // Prototype int Add(int a, int b = 3); // Definition</code>
Defining the function directly:
<code class="cpp">int Add(int a, int b = 3); // Both declaration and definition</code>
The default parameter definition is usually specified in the function declaration. This is because the compiler will only see the parameter declaration when it compiles code that calls the function. By specifying the default value in the declaration, the compiler can ensure that the function is always called with the correct number of arguments, even if some are missing.
Consider the following example:
lib.h
<code class="cpp">int Add(int a, int b = 3);</code>
lib.cpp
<code class="cpp">int Add(int a, int b) { ... }</code>
test.cpp
<code class="cpp">#include "lib.h" int main() { Add(4); }</code>
If the default parameter definition was specified in the function definition only, the compilation of test.cpp would fail with an error, as the compiler would not see the default value declaration. By specifying the default value in the function declaration, test.cpp will compile successfully, and the default value of 3 will be used for the missing argument.
The above is the detailed content of How do Default Parameter Values Work in C Functions?. For more information, please follow other related articles on the PHP Chinese website!