devxlogo

Default Arguments to Functions

Default Arguments to Functions

Question:
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 (!).

Answer:
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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist