Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Dec 1, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Default Arguments to Functions

Is it considered acceptable to use default argument initializers both in a definition of a function (e.g., void foo(int x =10) {...}) as well as its declaration? Stroustrup, in his only example, does not, but it seems reasonable and conforms to the grammar, doesn't it?

I've wondered about this because g++ (2.8.1) behaves strangely for member function definitions with default arguments. If they are actual ints (like 0) or global variables, it is fine, but if they are const ints, it complains about an inconsistency (!).

You should specify default parameter values in the function's prototype exclusively. The default values should not appear in the definition.

Note also that the declaration must be seen before you call the function. The One Definition Rule requires that repeated declarations of the same function must have the same default parameter values. Doing something like this:

 //file first.cpp
 void f (int x = 0);
 //file second.cpp
 void f (int x = 1);
is illegal. Instead, you should declare the function with its default parameter values in a single .h file and #include that file in every source file that refers to that function.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date