*write the prototype and header for a function called compute. The function should have three arguments : an int, a double, and a long (not necessarily in that order). The int argument should have a default value of 5,and the long argument should have a default argument of 65536. The double argument should not have a default value *
I always seem to mess these up, can anybody help me? This is what I have:
This won't work: int functionWithWrongDefaults(int x, int y = 4, int z, int q = 9);
It fails with this error:
'functionWithWrongDefaults': missing default parameter for parameter 3
But this will work: int functionWithGoodDefaults(int x, int y = 4, int z = 3, int q = 9);
Defaults must come at the end of the parameters list.
Once you start listing default parameters, all those after it must also have a default. They must all be
rightmost values.
Take note:
Default parameters can only be declared once
...
Best practice is to declare the default parameter in the forward declaration and not in the function definition
So, the prototype (the declaration) should contain the defaults. Omit those from the header, since they can only be defined once. You'll get a compilation error if you try to define the default parameters more than once.
1 2
Header : void compute(double D, int X, long L)
Prototype: void compute (double D, int X = 5, long L = 65536);
The order in the prototype and header must match exactly. But other than that, in general no, you can put data types in any order as long as the prototype and header match, but that must be the order in which you supply arguments when you call it. And default arguments must be the rightmost arguments, so those can't me moved around to the front of the parameter list.
Doing this: void func(int x, int y, double d, float f);
is no less valid than this: void func(float f, int y, double d, int x);
Although I would say the first is better because it doesn't mix the data types around too much.