Skip to main content
gamedev.net
🔒 Locked

Using Default Arguments

Started by BcS 3 replies 600+ views
Original Post
BcS
BcS
So, I''m reading about default argument values and both books I have show specifying the default values in the function prototypes but NOT in the actual function definition, as in:
#include <iostream>

using namespace std;

void printNumber(int num = 0);

int main()
{
    printNumber();
    return 0;
}

void printNumber(int num)
{
    cout << num;
}
But it seems to me that to be clear, you''d want to use the default values in the definition too, as in:
#include <iostream>

using namespace std;

void printNumber(int num = 0);

int main()
{
    printNumber();
    return 0;
}

void printNumber(int num = 0)
{
    cout << num;
}
I''ve tested both with Dev-C++ (version 4) and both programs work. But is the second version wrong? Why doesn''t any book say you can specify the default values in both the prototypes and definitions of the function? Is this not allowed in Standard C++?
drowner
drowner
stroustrup states it cannot be repeated or changed in subsequent declarations within the same scope. (pg 153, the c++ programming language special ed.)

So if you have a prototype I guess that''d be the right place to do it


------------------------------------------------------------
// TODO: Insert clever comment here.
------------------------------------------------------------// TODO: Insert clever comment here.
JTippetts
JTippetts
It makes more sense to me to put it in the prototypes anyway, especially if the prototypes are declared in a header file, as that is the file I refer to most commonly if I need to reference what parameters a certain function call requires. My header files are typically more organized, more compact, and more documented; not to mention, it is easier to find a function declaration or prototype in a header than hunting through or searching the source.

Also, in the case that the project is part of a third party library meant to be used by other people--people who might or might not have access to the source--putting default arguments in the header files might be the only way they will know a function even has default arguments.

Josh
vertexnormal AT linuxmail DOT org


Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.
jdhardy
jdhardy
Dev-C++ v4 uses an older gcc version (2.95.x) which ignores that little fact. Under Dev-C++ v5 (and gcc 3.x) it will choke if you have the default in the definition.

I just do this:

void foo(int bar, int baz = 5);

void foo(void foo(int bar, int baz/* = 5*/)
{
//etc.

}
Just as a reminder when I''m writing/editing the function.
BcS
BcS
Since Stroustrup and the latest version of gcc say so, I''ll only specify the default value in the prototype.

Thanks for you help, everyone.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.