int add (int x, int y=1)
int main ()
{
int result1 = add(5);
int result2 = add(5, 3);
result 0;
}
VS
int add (int x, int y)
int main ()
{
int result1 = add(5, 1);
int result2 = add(5, 3);
result 0;
}
What is the advantage of using the default function parameter, in term of execution speed, memory usage and etc? For beginner like me, I sometimes got confused before I realized this usage of default function parameter; isn't it coding without default function parameter made the codes easier to read?
Your add function is not a good example of how to use defaulted parameters, and you are correct that with one it is harder to read.
However, this not true for all functions. Consider std::vector::resize, which looks something like:
template<class T>
struct vector_imitation {
void resize(int new_size, T new_values=T());
};
Here, resizing without providing a value uses T(). This is a very common case, and I believe almost everyone finds the one-parameter call of resize easy enough to understand:
vector_imitation<int> v; // [] (v is empty)
v.resize(3); // [0, 0, 0] (since int() == 0)
v.resize(5, 42); // [0, 0, 0, 42, 42]
The new_value parameter is constructed even if it is never needed: when resizing to a smaller size. Thus for some functions, overloads are better than defaulted parameters. (I would include vector::resize in this category.) For example, std::getline works this way, though it has no other choice as the "default" value for the third parameter is computed from the first parameter. Something like:
template<class Stream, class String, class Delim>
Stream& getline_imitation(Stream &in, String &out, Delim delim);
template<class Stream, class String>
Stream& getline_imitation(Stream &in, String &out) {
return getline_imitation(in, out, in.widen('\n'));
}
Defaulted parameters would be more useful if you could supply named parameters to functions, but C++ doesn't make this easy. If you have encountered defaulted parameters in other languages, you'll need to keep this C++ limitation in mind. For example, imagine a function:
void f(int a=1, int b=2);
You can only use the given default value for a parameter if you also use given defaults for all later parameters, instead of being able to call, for example:
f(b=42) // hypothetical equivalent to f(a=1, b=42), but not valid C++
If there is a default value that will provide correct behavior a large amount of the time then it saves you writing code that constantly passes in the same value. It just makes things more simple than writing foo(SOME_DEFAULT) all over the place.
It has a wide variety of uses. I usually use them in class constructors:
class Container
{
// ...
public:
Container(const unsigned int InitialSize = 0)
{
// ...
}
};
This lets the user of the class do both this:
Container MyContainer; // For clarity.
And this:
Container MyContainer(10); // For functionality.
Like everything else it depends.
You can use it to make the code clearer.
void doSomething(int timeout=10)
{
// do some task with a timeout, if not specified use a reasonable default
}
Is better than having lots of magic values doSomething(10) throughout your code
But be careful using it where you should really do function overloading.
int add(int a)
{
return a+1;
}
int add(int a,int b)
{
return a+b;
}
As Ed Swangren mentioned, some functions have such parameters that tend to have the same value in most calls. In these cases this value can be specified as default value. It also helps you see the "suggested" value for this parameter.
Other case when it's useful is refractoring, when you add some functionality and a parameter for it to a function, and don't want to break the old code. For example, strlen(const char* s) computes the distance to the first \0 character in a string. You could need to look for another characted, so that you'll write a more generic version: strlen(const char* s, char c='\0'). This will reuse the code of your old strlen without breaking compatibility with old code.
The main problem of default values is that when you review or use code written by others, you may not notice this hidden parameter, so you won't know that the function is more powerful than you can see from the code.
Also, google's coding style suggests avoiding them.
A default parameter is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be
used. If the user does supply a value for the default parameter, the user-supplied value is used.
In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language)
Advantages of using default parameter, as others have pointed out, is indeed the "clarity" it brings in the code with respect to say function overloading.
But, it is important to keep in mind the major disadvantage of using this compile-time feature of the language: the binary compatibility and default function parameter does not go hand in hand.
For this reason, it is always good to avoid using default params in your API/interfaces classes. Because, each time you change the default param to something else, your clients will need to be recompiled as well as relinked.
Symbian has some very good C++ design patterns to avoid such BC.
Default parameters are better to be avoided.
let's consider the below example
int DoThis(int a, int b = 5, int c = 6) {}
Now lets say you are using this in multiple places
Place 1: DoThis(1);
Place 2: DoThis(1,2);
Place 3: DoThis(1,2,3);
Now you wanted to add 1 more parameter to the function and it is a mandatory field (extended feature for that function).
int DoThis(int a, int x, int b =5, int c=6)
Your compiler throws error for only "Place 1". You fix that. What about other others?
Imagine what happens in a large project? It would become a nightmare to identify it's usages and updating it rightly.
Always overload:
int DoThis(int a) {}
int DoThis(int a, int b {}
int DoThis(int a, int b, int c) {}
int DoThis(int a, int b, int c, int x) {}
Related
I have a function which executes a bunch of tests. Whenever a new test is created, the function gets one or two more lines. And - the result is pushed back into an array. So it goes something like this (simplified):
void foo(int *results) {
auto index { 0 };
results[i++] = test_1(some, args, here);
results[i++] = test_1(some, other_args, here);
results[i++] = test_2(some, args, here);
results[i++] = test_3(some, args, here);
// etc. etc.
}
void bar() {
auto results = new int/* magic */];
foo(results);
}
I want to use the number of statements in this function to allocate space for the results (the line in bar()). I cannot use a dynamically-reallocated structure like an std::vector or a list etc. - since I am precluded from allocating any memory due to hardware restrictions.
Now, I could just manually count the lines - and this would work. But then whenever I add another test I would have to remember to update the magical constant.
Is there some way to do the counting with the result usable for the "magic" expression?
Note: Since I'm a scrupulous man with no dignity, I am willing to stoop to the use of macros.
Speaking of macro hackery:
#include <iostream>
#define ADD_TEST(X) do { results[i++] = (X); (void)__COUNTER__; } while (0)
const int foo_start = __COUNTER__;
void foo(int *results) {
int i = 0;
ADD_TEST(100);
ADD_TEST(200);
ADD_TEST(300);
}
const int foo_end = __COUNTER__;
int main() {
int results[foo_end - foo_start - 1];
foo(results);
for (int i : results) {
std::cout << i << '\n';
}
}
It's slightly awful and __COUNTER__ is a non-standard extension in GCC and other compilers, but hey, it works.
The advantage is that it doesn't use any fancy C++ features, so in principle it should be compatible with older compilers and even C.
As you haven't specified any language version, though, did tag it with constexpr, I've solved this making use of C++17. This without any dirty macros. Instead, I'm relying on CTAD (Constructor template argument deduction).
First of all, I've assumed your functions are constexpr. That way, everything can be done at compile-time. (In the resulting code, you don't even see memory being used for the array.
constexpr int test_1(int a, int b, int c)
{
return a + b + c;
}
constexpr int test_2(int a, int b, int c)
{
return a * b * c;
}
This isn't strictly needed, however, it can move unneeded calculations to compile time. It also allows propagating constexpr upto the final variable. That way, you could guarantee that none of the calculations will happen at run-time.
static constexpr auto myArr = createFilledArray();
However, the most important part is CTAD. A new C++17 feature that allows deducing the template arguments of your class based on the values that are passed at the constructor.
Instead of first creating an array, I create the array directly with all the different values that you pass to it. Since you haven't provided any arguments in your example, I assume they are known at compile time, which is again required for the constexpr waterfall. However, more importantly, I assume the number of elements is known at compile time.
By constructing all arguments when calling the constructor of std::array, there is no need for specifying its template arguments (note also the auto as return type). This gets deduced as std::array<int, 3> for this example.
constexpr auto createFilledArray(){
std::array a
{
test_1(1, 2, 3),
test_1(4, 5, 6),
test_2(7, 8, 9),
};
return a;
}
int main(int, char**)
{
return myArr.size(); // Returns 3
}
Code at compiler explorer
From what I'm aware, there is a proposal for C++20 that is intended to make std::vector constexpr. However, none of the compilers I've tested at compiler explorer support this. This will most likely allow you to write code based on std::vector and use that at compile time. In other words, the allocated memory that represents your data, will be part of your executable.
A quick attempt of what your code could look like can be found here at compiler explorer. (However, it ain't compiling at this point)
Lets say I have a function
void doStuff(vector<int> &a, int b, vector<int> &c> {
c = vector<int>(a.size());
for (int i = 0; i < a.size(); i++) {
c[i] = a[i] + b;
}
}
obviously, upon seeing the function, we know that "c" is the output.
For anybody who hasn't seen the function definition though, it remains a mystery unless i name c something like "output_c". Maybe I'm just being vein but I don't like naming things "ouput_xxx", is there any syntax candy for letting the user of the function know that its supposed to be the output?
Syntax, by itself, can be a guide to indicate which one is an input argument and which one is an output argument. However, an output argument can also serve as an input argument too. You cannot tell that by just looking at the signature.
Examples:
int foo(int arg); // The argument is copy by value. It can only be an input argument.
void foo(std::vector<int> const& arg); // The argument is by const&.
// It can only be an input argument.
void foo(std::vector<int>& arg); // The argument is by &. It can be:
// 1) an output argument.
// 2) an input and output argument.
// 3) an input argument (bad practice)
You could add a preprocessor directive:
#define OUT
and put it in the parameter list like so:
void doStuff(vector<int> &a, int b, OUT vector<int> &c) ...
I think I've seen some APIs do something like this. That way it is explicitly stated in the function signature but you don't have to modify the variable names. The code is also unchanged at compile time since OUT is not defined to be anything, it is just a defined symbol.
I think, though, I would rely on your own documentation when writing the function and/or return-by-value instead of doing something like this. You could also make use of the const keyword to flag a parameter that is guaranteed not to change - that's what the syntax is designed for.
So I have a function with several parameters that will need to perform several tasks based on these parameters. But when I call this function I may not need it to perform some of the tasks in it.
For example my function has parameters (int x, int bin, int value) but sometimes when I call it I don't want it to evaluate the part of the function using int value. How can I accomplish this? I've heard of using optional arguments which default the argument to 0 if I don't specify it but that is not what I want. What I want is this, if I provide a value for "int value" then I want the part of my function using this value to evaluate, otherwise, ignore it.
I suggest using function overloading:
void foo(int x, int bin) {
//...
}
void foo(int x, int bin, int value) {
foo(x, bin);
// extra stuff using value...
}
But you could also make value a pointer and use nullptr to signify it shouldn't be used.
Here is another option. In this case if the function is called with only two parameters value will be initialized to a sentinel (-1 in this case) and can be checked in the code.
void foo(int x, int bin, int value=-1) {
// x stuff
// bin stuff
if (value != -1) {
// value stuff
}
}
This will only work if there is some invalid value though which could be 0, -1, or the maybe the max value of an int. Function overloading is probably a better option though.
I am reading this tutorial about function pointers which said that function pointers can replace a switch statement
http://www.newty.de/fpt/intro.html .
Can anyone clarify?
We have a switch statement like this:
// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
// Execute example code
void Replace_A_Switch()
{
cout << endl << "Executing function 'Replace_A_Switch'" << endl;
Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
As you can see, the Replace_A_Switch() function as an example is very unclear. Supposed we need to point the function pointer to one of 4 arithmetic functions(Plus,Mins,Multiply,Divide). how can we know which one we need to point to? We have to use the switch statement again to point the function pointer to the arithmetic functions , right?
It will be like this one**(please the comment in the code)**:
void Replace_A_Switch()
{
.....................
..........
//How can we know this will point to the &Minus function if we don't use the switch statement outside?
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
So in summary, what is the advantages of function pointer, it always said that the function pointer a late-binding mechanism , but in this tutorial i dont see any advantage of the function pointer for late binding.
Any help are very appreciated. Thanks.
What you're saying is pretty well true, you still need to decide somewhere what function pointer to use.
What you're looking at though is a pretty simple, contrived example for explanation purpose. It shows how you can leverage a function pointer. In this case it might be pointlessly complicated but a real case would probably be too complicated to use to instruct in this basic concept.
The difference becomes much clearer when you've got a lot of functions that have the same switch, or a switch with subsets of the same set. The difference is all the same though (this is also important). In that case, why rewrite it a bunch of times?
It also opens your code for a change in how the decision is made. Maybe you want to invert '+' and '-' for whatever reason. Change the point where you make the pointer and all the client code catches up.
Finally, what if you don't even need to make the decision? Instead of replacing the switch for example, what if you just wanted to do the addition version? Obviously addition is too simple a task for this level of design, but again it's just an example.
All this is true whether you're using function pointers or a class hierarchy. Someone has to decide what the input will be. What these constructs do is provide you a method to compose different bits into a running program. It also separates the part that is responsible for deciding which version of things to use from the using of those things. There are a lot of different ways to approach that creation (see creational design patterns for some).
As the tutorial states there are no advantages and the basic calculator is simply an example. The main use of function pointers is to allow the API-dev to define a function, which does something that is not known at the time the API is created.
A better example is probably qsort, which takes a comparison function. Thanks to this function-pointer argument it is possible to implement the sort in a generic way. Since you could not possibly know what kind of data needs to be sorted you can't know how the <,=,> operators have to be implemented. Thus you expect the caller to provide a function that implements the comparison thereby avoiding this dilemma.
In general, function pointers are often useful if you want to program something in a generic way. Its use is that of function-arguments in other languages. If someone asked you to implement a simple reduce function for example, you could come up with something like this:
void reduce(void *data, size_t nmemb, size_t size,
void (*op)(void *, void *), void *res){
int i;
for (i = 0; i < nmemb; ++i){
op(data, res);
data = (void *)((unsigned char*)data + size);
}
}
Clearly it is very advantageous over rewriting this for operations like multiply, add, and more complex ones all over again with the respective function replacing op.
I can see how you can convert your '+', '-' etc into an enum, and store the 4 func pointers into an array ordered by the enum order. After that arr[op] is the function you want, just execute that.
Alternatively a std::map<String, FuncType> map from + -> &Plus.
as from what i see..
the pt2Func is a name defined for pointer which references a function
you can see how it works in the main where it is being called
(removed the comment to make it more readable)
Switch_With_Function_Pointer(2, 5, &Minus);
&Minus here is a pointer that references to your function Minus
this is stupid as you are calling a function to reference another function by using a pointer.
There is no benefit and it does nothing special.. its just another more complicated way to call the Minus function
the Switch function however is just a normal switch encapsulated in a function for reusability
My actual question is it really possible to compare values contained in two void pointers, when you actually know that these values are the same type? For example int.
void compVoids(void *firstVal, void *secondVal){
if (firstVal < secondVal){
cout << "This will not make any sense as this will compare addresses, not values" << endl;
}
}
Actually I need to compare two void pointer values, while outside the function it is known that the type is int. I do not want to use comparison of int inside the function.
So this will not work for me as well: if (*(int*)firstVal > *(int*)secondVal)
Any suggestions?
Thank you very much for help!
In order to compare the data pointed to by a void*, you must know what the type is. If you know what the type is, there is no need for a void*. If you want to write a function that can be used for multiple types, you use templates:
template<typename T>
bool compare(const T& firstVal, const T& secondVal)
{
if (firstVal < secondVal)
{
// do something
}
return something;
}
To illustrate why attempting to compare void pointers blind is not feasible:
bool compare(void* firstVal, void* secondVal)
{
if (*firstVal < *secondVal) // ERROR: cannot dereference a void*
{
// do something
}
return something;
}
So, you need to know the size to compare, which means you either need to pass in a std::size_t parameter, or you need to know the type (and really, in order to pass in the std::size_t parameter, you have to know the type):
bool compare(void* firstVal, void* secondVal, std::size_t size)
{
if (0 > memcmp(firstVal, secondVal, size))
{
// do something
}
return something;
}
int a = 5;
int b = 6;
bool test = compare(&a, &b, sizeof(int)); // you know the type!
This was required in C as templates did not exist. C++ has templates, which make this type of function declaration unnecessary and inferior (templates allow for enforcement of type safety - void pointers do not, as I'll show below).
The problem comes in when you do something (silly) like this:
int a = 5;
short b = 6;
bool test = compare(&a, &b, sizeof(int)); // DOH! this will try to compare memory outside the bounds of the size of b
bool test = compare(&a, &b, sizeof(short)); // DOH! This will compare the first part of a with b. Endianess will be an issue.
As you can see, by doing this, you lose all type safety and have a whole host of other issues you have to deal with.
It is definitely possible, but since they are void pointers you must specify how much data is to be compared and how.
The memcmp function may be what you are looking for. It takes two void pointers and an argument for the number of bytes to be compared and returns a comparison. Some comparisons, however, are not contingent upon all of the data being equal. For example: comparing the direction of two vectors ignoring their length.
This question doesn't have a definite answer unless you specify how you want to compare the data.
You need to dereference them and cast, with
if (*(int*) firstVal < *(int*) secondVal)
Why do you not want to use the int comparison inside the function, if you know that the two values will be int and that you want to compare the int values that they're pointing to?
You mentioned a comparison function for comparing data on inserts; for a comparison function, I recommend this:
int
compareIntValues (void *first, void *second)
{
return (*(int*) first - *(int*) second);
}
It follows the convention of negative if the first is smaller, 0 if they're equal, positive if the first is larger. Simply call this function when you want to compare the int data.
yes. and in fact your code is correct if the type is unsigned int. casting int values to void pointer is often used even not recommended.
Also you could cast the pointers but you have to cast them directly to the int type:
if ((int)firstVal < (int)secondVal)
Note: no * at all.
You may have address model issues doing this though if you build 32 and 64 bits. Check the intptr_t type that you could use to avoid that.
if ((intptr_t)firstVal < (intptr_t)secondVal)