In C , functions can be declared with default parameters, allowing them to be called without providing values for all the arguments. However, the syntax for specifying the default parameter can vary.
Case 1:
<code class="cpp">int Add(int a, int b = 3); int Add(int a, int b);</code>
Case 2:
<code class="cpp">int Add(int a, int b); int Add(int a, int b = 3);</code>
Both syntaxes are valid. However, the standard and recommended approach is Case 1, where the default parameter is specified in the function declaration. This is because:
Consider the following scenario:
In Case 1:
The compiler will see the default parameter declaration in the header file during compilation of test.cpp. This ensures that the call to the function in test.cpp is valid, even though the default parameter was not explicitly provided.
In Case 2:
The compiler will not see the default parameter declaration in the header file during compilation of test.cpp, as it is only defined in the implementation file (lib.cpp). This will result in a compilation error in test.cpp, as the default parameter was not declared.
Therefore, specifying the default parameter in the function declaration (lib.h) is the standard way to ensure consistent behavior across different compilation units.
The above is the detailed content of Where should default parameters be defined in C : declaration or definition?. For more information, please follow other related articles on the PHP Chinese website!