Calling multiple functions using some generic function call in C - c

I want to be able to call multiple functions using a single generic function call.
Currently I am trying to implement something like this:
main()
{
generic();
}
A(){.....};
B(){.....};
C(){.....};
Where I call from main() some generic function, which, in turn, is supposed to be able to call the functions: A(), B(), C().
How can I implement this in C?

You can do it by using function pointers. Please refer on "how to use function pointers in C"

You have to use function pointers as below.
#include<stdio.h>
void A(void);
void B(void);
void C(void);
typedef void (*foo_ptr_t)( void );
foo_ptr_t foo_ptr_array[3]; //fucntion pointers of type foo_ptr_t
main()
{
int i = 0;
foo_ptr_array[0] = A; //assign function to each function pointer
foo_ptr_array[1] = B;
foo_ptr_array[2] = C;
for(i = 0; i<3; i++)
foo_ptr_array[i](); //call functions using function pointer
}
void A()
{
printf("We are in A\n");
}
void B()
{
printf("We are in B\n");
}
void C()
{
printf("We are in C\n");
}

You can use function pointers, if all functions you want to call have same prototype.

Related

Merging two similar c functions into one

I have two functions that look like the ones down below and I am trying to merge the two with a function called function3 however I don't want it to check the parameter 'function' everytime it enters the while loop as it is a very poor way to do it. I am wondering if I can merge the two with only one if statement.
void function1(){
int value,a,b;
while(condition){
value=a*b;
}
}
void function2(){
int value,a,b;
while(condition){
value=a+b;
}
}
//merge two functions
void function3(int function){
int value,a,b
while(condition){
if(function==1){
value=a*b;
}
else{
value=a+b;
}
}
}
It is not clear from the code you posted what you intent to do, since you don't actually do anything with the values you calculated.
Aside, I think that you are looking for an array of functions or an array of pointers to functions.
You can use the variable function to access the function that you need, assuming it matches the array index of that function.
int function1(int a, int b) {
return a * b;
}
int function2(int a, int b) {
return a + b;
}
int (*f[])(int, int) = { function1, function2 };
void call_function(int function, int a, int b) {
// check that "function" is within bounds of the array
if (function < 0 || function >= sizeof(f) / sizeof(f[0])) {
// handle out of bounds
}
// call appropriate function
int ret_val = f[function](a, b);
return;
}

How can I use a callback to pass an integer to a pointer in C?

I have a function that prints 'Hello' and an integer.
I would like to use a callback function that passes the integer into the first function A.
//FUnction Pointers in C/C++
#include<stdio.h>
void A(int ree)
{
printf("Hello %s", ree);
}
void B(void (*ptr)()) // function pointer as argument
{
ptr();
}
int main()
{
void (*p)(int) = A(int);
B(p(3));
}
Desired result would be 'Hello 3'. This doesn't compile.
#include<stdio.h>
void A(int ree)
{
printf("Hello %d", ree); // format specifier for int is %d
}
void B(void (*ptr)(int), int number) // function pointer and the number as argument
{
ptr(number); //call function pointer with number
}
int main()
{
void (*p)(int) = A; // A is the identifer for the function, not A(int)
B(p, 3); // call B with the function pointer and the number
// B(A, 3); directly would also be possible, no need for the variable p
}

How do I access variables in C from different functions?

my question is how does the function malloc_queue() can access variables from init_queue() without giving any arguments!
For example:
The main.c:
if (init_queue()) {
malloc_queue()
}
init_queue() creates the variable que:
int init_queue{
struct Queue *que;
return 1;
}
malloc_queue() want to do something with the variable que from init_queue():
void malloc_queue{
struct Queue *que = (struct Queue*)malloc(sizeof(struct Queue));
return;
}
but that doesnt work since malloc_queue doesnt know what que is. Are there any possible ways without giving any arguments?
Maybe you want a static variable outside functions, which has scope inside the residing file after its definition.
Check this code:
#include <stdio.h>
static int x = 0;
void a() {
x = 5;
}
void b() {
x*=2;
}
int main(int argc, char * argv[]) {
printf("%d\n", x);
a();
printf("%d\n", x);
b();
printf("%d\n", x);
return 0;
}
Just as the comments suggested, read about c scopes.
If you need to declare struct other than primary types, you might need to declare a pointer to structure as the static variable outside function, then allocate memory (e.g malloc()) inside one of your functions.

All the functions in c are globally defined, then why we need to pass them to function as argument?

In c, we have to define all the functions globally. while studying function pointer i got some program where programmer passes function name as parameter to other function. so why we need to pass function to other function if they all are globally defined?
here i am giving small sample program :
#include<stdio.h>
void bsort(int arr[],int n,int (*compare)(int,int)) //bubble sort
{
int i,j,temp;
for(i=0;i<n;i++){
for(j=0;j<n-i-1;j++){
if(compare(arr[j],arr[j+1]) > 0 ){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int compare(int a,int b)
{
if(a > b) return 1;
return -1;
}
void main()
{
int i;
int arr[5]={6,5,1,9,2};
bsort(arr,5,compare);
for(i=0;i<5;i++)
printf("%d ",arr[i]);
}
in this code, if we remove 3rd argument in definition and calling part of bsort function then also our program will give us same output.so for function pointer this program doesn't make sense.
can you please do some modification in this code and make it good example for function pointer.
Thanks.
Your code does not actual need passing functions as parameters. But your example is rather didactic to make you understand how function pointers work.
However it's important to understand them as they might become very useful especially when dealing with libraries loaded at runtime. There are tons of examples where function pointers are really a good tool.
Here's one:
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
double doOperation(double arg, double (*func)(double))
{
return (*func)(arg);
}
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
printf ("%f\n", doOperation(2.0, cosine);
dlclose(handle);
}
You open a library, search for the cosine function, and then pass it as an argument to doOperation.
You can also look here for more info.
Function pointers are used when you might need to change the behavior of your function call depending on some dynamic requirement.
This page sums it up short and sweet:
A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior. For instance, every time you need a particular behavior such as drawing a line, instead of writing out a bunch of code, all you need to do is call the function. But sometimes you would like to choose different behaviors at different times in essentially the same piece of code.
A few excellent examples are available there are well.
You pass a function [pointer] to another function because you want to dynamically direct which function the receiver calls. Or more precisely, because the receiver function is built to allow you to do so, thereby requiring you to do so. The pointed-to function does not need to be available at the time the receiver is compiled.
The comparison function required as a qsort() argument is the prototypical example.
Q: Why pass a function to another function?
Without re-writing bsort(), code can sort more than 1 way by only changing the compare function.
#include <stdio.h>
#include <stdarg.h>
int compare_up(int a,int b) {
if(a > b) return 1;
return -1;
}
int compare_down(int a,int b) {
if(a < b) return 1; // reverse the compare
return -1;
}
int compare_random(int a,int b) {
return rand() & 1; // mix them up
}
int main(void) {
int i;
int arr[5]={6,5,1,9,2};
bsort(arr,5,compare_up);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
bsort(arr,5,compare_down);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
bsort(arr,5,compare_random);
for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");
return 0;
}

What do I put in the function prototype when using that function with different parameters?

I want to use a function to fill different arrays with data by calling that function thrice.
// Function prototype
void fill_array();
int main()
{
int bin_array[15],
prb_array[15],
seq_array[15];
fill_array(bin_array);
fill_array(prb_array);
fill_array(seq_array);
return 0;
}
My question is, what parameters should I put up at the function prototype? All three?
// Function prototype
void fill_array(insert parameter here);
In the prototype, you don't even have to put any name at all, just the type:
void fill_array(int[]);
When you define the function, however, you need a name. However, it can be whatever you want:
void fill_array(int joe[]) {
//...
}
Edit: Although not directly related to the problem at hand, birryree makes an excellent point. You should usually pass the size of an array as well, since otherwise fill_array doesn't know how big the array is:
void fill_array(int[], int);
void do_stuff() {
int bin_array[15],
prb_array[15],
seq_array[15];
fill_array(bin_array, sizeof(bin_array) / sizeof(int));
fill_array(prb_array, sizeof(prb_array) / sizeof(int));
fill_array(seq_array, sizeof(seq_array) / sizeof(int));
}
void fill_array(int bob[], int length) {
for(int i = 0; i < length; i++) {
bob[i] = i * 3;
}
}

Resources