How can I create a function pointer to a function where some parameters are set to be fixed upon the definition.
Here is an example what I mean:
Let's say I have the function
int add (int n, int m) {
return n+m;
}
and the function pointer type
typedef int (*increaser)(int);
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open. Something along the lines of
increaser f = &add(1,x);
How can I accomplish this?
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open.
There is no such thing in C. The closest you can come is to create a wrapper function and make a pointer to that:
int add1(int x) {
return add(1, x);
}
increaser f = &add1;
If you don't need a pointer to the function then you can use a macro:
#define increaser(x) add(1, (x))
C does not support doing this directly. In C++ there is std::function and bind which can achieve this however.
None the less for a pure C solution the closest you can reasonably get is defining a new function that calls add like:
int increment(int input) {
return add(1, input);
}
Then you can do:
increaser f = &increment;
Related
I'm currently practising C and learning pointers and arrays. I watched a tutorial where the instructor changed the function from int aFunction() to void aFunction(). Of course, he didn't say why — that's why I'm here. So I'm wondering: when and why should someone use void as the return type for a function.
In C, you have to tell the compiler what are each of the types of the variables you declare. That is why you have things like int and char*.
And functions’ return values are no different. Compiler has to know what each of your functions return types are to work properly. Now if you have a function like add(int a, int b) typically you would want its return type to be of integer, that is why you would define it as
int add(int a, int b)
{
return a+b;
}
Now consider you have a function that doesn’t return anything at all, now you need to tell your compiler that this function returns nothing. That is why void is used. You use void when the function does something but in the end doesn’t need to return any value to the program it was called from. Like this one:
void printAdd(int a, int b)
{
printf(“a + b = %d”, a+b);
}
We are doing a bunch of stuff here but the result from the addition is not returned or stored but rather printed to the screen.
You can use the first function add() like this:
int abc = add(5, 7);
// abc is 12
while you can only use the second function like
printAdd(5, 7);
// you cannot store the value because nothing is returned.
// 5 + 7 = 12 is printed to the screen
The token(s) that precedes the function name in the function declaration is the type of the value that the function returns. In this case there is just one token, but type names may consist of multiple tokens. When you want to return an integer object, you can specify the return type to be int. When the function won't return anything, you use void return type.
Say I had a program where the user could select a number between 0-10. Each number would then correspond to the calling of a certain function. In Python, I know I could just create an array of function names, index into it with the selected option, and then call the function. How would I implement this in C? Or is it even possible?
Here is an example how to do it. Please note that all functions must have the same signature, but of course you can change that from my funptr type to for example a function that has void return or takes a char and not two ints.
// Declare the type of function pointers.
// Here a function that takes two ints and returns an int.
typedef int (*funptr)(int, int);
// These are the two functions that shall be callable.
int f1(int a, int b) { return a + b; }
int f2(int a, int b) { return a - b; }
// The array with all the functions.
funptr functions[] = {
f1,
f2,
};
// The caller.
int call(int i, int a, int b)
{
return functions[i](a, b);
}
The only problem that I can see in the solution from above is that there is no check for the array index (you may get some tricky problems).
To make the code more robust, you can add a check for the index (boundaries), like
add one if statement inside of function "call" where you check the parameter i (not to be bigger than the maximum value)
I need to figure out how to use a void type function to change a value in another function, so I'm trying to write a practice program that uses a procedure to change an integer from 5 to 4 and then prints the new integer (should be 4).
#include <stdio.h>
#include <stdlib.h>
void change(int x)
{
x = 4;
}
int main(int argc, char **argv)
{
int z = 5;
change(z);
printf("%d\n",z);
return 0;
}
This prints 5 at the end. I can tell there's some kind of issue with scope here, but I can't figure out how to resolve it. I also can't print within the procedure, so that solution is out of the question. I'd really appreciate any help!
To change a variable within another function, that isn't in the scope of the function, you must pass the variable by pointer.
void change(int *x)
{
*x = 4;
}
And call the function using change(&z).
If the variable isn't passed by pointer, then only the variable inside the scope of the function will change, but not its argument.
In C, function arguments are always passed by value. This means that any changes made to a value in a function are not reflected in the caller. That is what's happening in your case.
Fortunately, you can pass a pointer (by value of course) instead. This allows you, via dereferencing, to change the value that the pointer is pointing to.
To do this, adjust the prototype of your function to
void change(int* x)
Then, within that function, use
*x = 4;
And, finally, call the function using
change(&z);
You need to pass the address of the variable and then you can change the value of the variable.
void change(int *x)
{
*x = 4;
}
Now the invoking function will have new value of x which is 4.
You can pass a pointer to the function, like so:
void change(int *x)
Is it possible to define an array of function pointers (and the functions don't have se same input argument ) as indicating in the following code ?
If yes what I have to put in the function definition int (*handler)(/*what Ihave to put here ?*/);
struct handler_index {
const char *name;
int (*handler)(/*what Ihave to put here ?*/);
};
int handler0 (int a, int b)
{
printf("%d\n",a+b);
}
int handler1 (int a, int b, int c)
{
printf("%d\n",a+b+c);
}
int handler2 (int a, int b, int c, int d)
{
printf("%d\n",a+b+c+d);
}
const struct handler_index handler_index[] = {
[0] = {"handler0", handler0},
[1] = {"handler1", handler1},
[2] = {"handler2", handler3},
};
Just put nothing:
int (*handler)();
it means the function has an unspecified (but non-variable) number and types of parameters.
Any function that returns an int and with a fixed variable number of parameters can be assigned to handler.
Whilst int (*handler)() will indeed allow variable number of arguments for th function, I fail to see any benefit in this. Function pointers are useful when you have a piece of code that takes something, finds the "right thing to do" (e.g comparing the "name" with some input from elsewhere), and calls the function pointer to do whatever it has to do. The function pointer calling code needs to know how many arguments the function has (how else would it pass the right number and order of arguments.
I don't actually see any meaningful use of this at all. Yes, you can pass a variable number of arguments to a function, but the code HAS to know what arguments the function takes.
Unless the arguments are somehow specified in the definition of the struct - but then you need to define different content for the struct to allow for that.
I would suggest that you need to think about what you are trying to achieve, and then come up with a solution to the problem, most likely using a different method.
Put nothing. Just empty brackets.
int (*handler)();
I was wondering if it is possible in C (89/90) to chain function calls, and where it is defined in the C spec. I assume this isn't possible since a google search reveals no mention of it.
I thought of this because of a related conversation with a friend of mine where he told me that given a function returning a struct, you cannot perform any operations on said struct within the same statement; instead, you have to assign the result of the function to a variable, and then manipulate the struct via the variable instead of directly from the function result itself. This leads me to believe that you can't chain functions either, but I can't seem to find these limitations discussed in the spec.
Edit : Sorry, I should have been specific on the return value. Assuming the function returns a function pointer, is it possible to dereference and call the result within the same statement, in fluent fashion?
For example, assuming getFunc returns a function pointer :
(*getFunc(getFuncParam))(otherFuncParam)
Or in the struct case, assuming a struct with an int member called count:
funcReturnsStruct(param).count++
Here's what function chaining looks like in C:
post_process(process(pre_process(data)));
Obviously, your friend is wrong. As long as the functions cooperate by accepting and returning the same type of value you can chain the calls all you like.
Contrast this with something like
data.pre_process().process().post_process();
The big difference is that in C (which has no encapsulation, hence no classes) functions have center stage while in more modern OO languages it's objects that get more attention.
Update: Sure it's possible to chain no matter what each function might return. For example:
int increase(int x) {
return x + 1;
}
typedef int (*increase_fp)(int);
increase_fp get_increase() {
return increase;
}
int main(void) {
printf("%d", get_increase()(1));
return 0;
}
See it in action.
a friend of mine where he told me that given a function returning a struct, you cannot perform any operations on said struct within the same statement
Your friend is correct in the sense that the return value of a function cannot be the target of an assignment (it's not an lvalue). IOW, you can't do something like
int foo(void) { int x = 5; return x; }
...
foo() = 6;
However, if the return type of a function is a struct or a union, you can apply the component selection operator to the return value, such as
int x = foo().memb;
Similarly, if the return type of the function is a pointer to a struct or a union, you can write
int x = foo()->memb;
And if the return value is a pointer to another function, you can call that other function like so:
int bar(int x) { ... }
int (*foo)(int x) { return bar; }
int x = foo(x)(y); // or (*foo(x))(y) -- the result of foo(x) is
// called with the argument y
although anyone who has to maintain or debug your code may beat you severely for it.
What you cannot do is something like
foo().memb= ...;
foo()->memb = ...;
which wouldn't make sense anyway, because the lifetime of the value returned by foo ends when the statement ends - you wouldn't be able to retrieve that modified value.
Your friend is wrong.
If we have:
struct Point3
{
float x, y, z;
};
const Point3 * point3_get_origin(void);
then you can certainly do:
printf("the origin's y coordinate is %f\n", point3_get_origin()->y);
The function returns a value of the given type, so the call of the function can be used wherever such a value is needed in an expression.
Do you mean something like this?
typedef void (*CALLBACK)(void);
CALLBACK getCallback();
void test()
{
getCallback()();
}
It compiles with no warning in GCC 4.6.1 (default std).
There's a much faster and easier way to answer this than posting here: try it.
#include <stdio.h>
struct s {
int a;
} s;
struct s * getS() {
s.a = 13;
return &s;
}
int main(int argc, char * const argv[]) {
printf("%d\n", getS()->a);
return 0;
}
% gcc test.c -o test -Wall -pedantic
% ./test
13
%
Not so much as a pedantic warning. Expected output. Looks like it's perfectly fine. However, as has been pointed out, it would be better to store the return value and check for errors.