dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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