How to put a function as an argument in C? - c

I would like to execute a function given in the paramater of a function. Let me explain with an example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int object() {
printf("Hello, World!");
return 0;
}
int run_func( int a_lambda_function() ) {
a_lambda_function();
return 0;
}
int main() {
run_func( object() );
return 0;
}
Now, I want to run "object()" in the parameters of "run_func(int a_lambda_function()").
When I run it, It returns an error. How would I achieve this is full C?
Restrictions I have:
Absolutly No C++ allowed.

Functions can be passed as arguments or stored into variables as function pointers.
The definition for a function pointer compatible with your object function is int (*funcp)() ie: a pointer to a function taking an unspecified number of arguments and returning int.
In modern C, functions with an unspecified number of arguments are not used anymore, and functions taking no arguments must be declared with a (void) argument list.
Here is a modified version:
#include <stdio.h>
int object(void) {
printf("Hello, World!");
return 0;
}
int run_func(int (*a_lambda_function)(void)) {
return a_lambda_function(); // can also write (*a_lambda_function)()
}
int main() {
return run_func(object);
}

Related

when i try to call a function it shows error

I am pretty new to coding. I used a simple code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
Sayhi();
return 0;
}
void Sayhi()
{
printf("hi");
}
So when I compile the code it says function "sayhi" was not declared in this scope.
I even tried a different code which used "void" as a function but it didn't work.
This should work - simply declare and define "Sayhi()" before you use it:
#include <stdio.h>
#include <stdlib.h>
void Sayhi();
{
printf("hi");
}
int main()
{
Sayhi();
return 0;
}
A "better" approach would be to create a prototype for "Sayhi()":
#include <stdio.h>
#include <stdlib.h>
void Sayhi(void);
int main()
{
Sayhi();
return 0;
}
void Sayhi();
{
printf("hi");
}
Q: So what's a "prototype"?
https://www.programiz.com/c-programming/c-user-defined-functions
A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type. It doesn't
contain function body.
A function prototype gives information to the compiler that the
function may later be used in the program.
Prototypes should always list the function's parameters. If no parameters, it should list "void".
The value of prototypes shines as your application increases in size and complexity. You'll want to move code OUT of "main()" and into separate .c source files (e.g. "mycomponent.c") and corresponding header files (e.g. "myheader.h").
One additional note: you should always NAME the variables in your prototypes (e.g. void myfunc(int i);.
Q: Do you understand why you were getting the compile error (the function needed to be declared somehow before you used it), and how you can fix it?

Assigning function to function pointers

I worte a test program to understand callback functions and function pointers.The program is given below.
My question is while assigning
cb_display = (void*)display_struct;
I have to cast the function to a void*. Why is this required even when the return type of function is void?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int a;
char b[16];
}myst_t;
void (*cb_display)(void*);
void display_struct(myst_t *st){
fprintf(stdout, "a -> %d b -> %s \n",st->a,st->b);
}
int main()
{
myst_t myst;
myst.a = 789432;
strncpy(myst.b,"helloabcd",9);
cb_display = (void*)display_struct;
cb_display(&myst);
return 0;
}
cb_display = (void*)display_struct;
is actually also not valid in C. Don't do it. You cannot assign a void * to a function pointer.
To fix your issue declare your function pointer as:
void (*cb_display)();
It means it matches a function that return no value and takes an unspecified number of parameters. You then don't need any cast. Also please note as it was pointed by Olaf in the comments that a function declarator with () while valid is an obsolescent C feature.
Of course if you will only pass functions like display_struct with a myst_t * parameter, you can also declare cb_display as: void (*cb_display)(myst_t *);
Changing void (cb_display)(void);
To typedef void (cb_display)(void);
May work.

why does the compiler give a warning for unused function?

I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.
Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.
You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error

Warning: Variable is unitialized in this function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "scanner.h"
int WhatFell(char *typeoffood)
{
if (strcmp(typeoffood,"meat") == 0);
return 1;
}
void getData(char *typeoffood)
{
printf("What fell on the floor? ");
typeoffood = readToken(stdin);
return;
}
int main(int argc, char **argv)
{
char *typeoffood;
int x;
getData(typeoffood);
x = WhatFell(typeoffood);
printf("%s\n",typeoffood);
printf("%d\n",x);
return 0;
}
eat.c: In function ‘main’:
eat.c:14:12: warning: ‘typeoffood’ is used uninitialized in this function [-Wuninitialized]
getData(typeoffood);
^
A few notes:
'readToken' is found in the "scanner.h" inclusion and simply is a safe version of scanf() for strings.
Also please just focus on the error, this is just a snippet of code I wrote seeings if I would be able to use a function getData for string input in my program.
I'm trying to use a function to ask for user string input (which I can do fine with integers/reals) and then use the string to run another function, but I keep getting all these weird warnings though and if I run it i get a segmentation fault.
char *typeoffood;
int x;
getData(typeoffood);
typeoffood is not initialized but passed to getData() so would receive uninitialised data. NB: The numbers 12:14 in the message tell you the line numbers relevant to the error.
You should pass typeoffood as a pointer to a pointer:
getData(&typeoffood);
and give getData() the prototype:
void getData(char **);

Programming with functions using C. The functions are not executed

I'm learning C and doing the exercise of the function chapter. So i have written a small programm with 3 files and two small functions. Sincerly it does not work. I have no errors, the functions are simply not executed and i don't know why.
First of all this is my headerfile which only declares my functions.
//employee.h
int addEmployee(void);
int printEmployee(int i);
So the next file is for the definition of the functions.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int numE;
int i;
int addEmployee(void)
{
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
return i;
}
int printEmployee(int i)
{
printf("%d", i);
getchar();
getchar();
return i;
}
And the last file is used to execute the functions.
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
Using
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
you're basically declaring 2 new functions with 0 arguments.
You're not calling your "old" functions.
This should work, as others have pointed out:
int main ()
{
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Because you're calling addEmployee(), storing it's result to emp and then printing emp using printEmployee. Since printEmployee is declared with one parameter, you just put emp in and it will work.
When you call a function you do not put the return type in front of the call. The call is simply the name of the function and any parameters you are calling it with. So your main function should look like this:
int main() {
addEmployee();
printEmployee(1);
return 0;
}
EDIT: So in your employee.c file, you are trying to use addEmployee() to take a number of employees from the command line and store it in the variable i right? And you want printEmployee() to tell you how many employees were entered? Here's how you would do that.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int i;
int addEmployee(void)
{
int numE;
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
}
int printEmployee()
{
printf("%d", i);
getchar();
getchar();
}
Here's what I did.
First, I made numE a variable local to the addEmployee function that uses it. Generally you should keep variable scope as small as possible. That means keep them down to the lowest level they are used. In this case, numE is only needed by addEmployee() so that's its scope.
Second, I removed the parameter from int printEmployee(int i). It was overriding your i variable at the file level. So you were storing the number read into numE in i but then when you entered printEmployee() you were creating a new, empty i that hid it. When you called printEmployee(1) from main, you were passing the value 1 into i in printEmployee(int i). By removing the parameter, you stop hiding employee.c's i.
Finally, I removed the returns. A function doesn't have to return anything in C. And if you are not going to use the return, then it's just an extra line of code to include it.
There's one more change you'll have to make to make this work, in your lab6.c file. Remove the parameter from the call to printEmployee()
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
addEmployee();
printEmployee();
return 0;
}
Should work the way you expect it now.
you want:
int main ()
{
addEmployee();
printEmployee(1);
return 0;
}
Change this:
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
To this:
int main ()
{
addEmployee();
printEmployee();
return 0;
}
You're re-declaring the functions instead of calling them.
You'll also have to change your printEmployee function to not accept an integer argument; it seems like it should just be using the same global variable as addEmployee. This is a bad idea though; global variables are generally to be avoided. addEmployee should probably return the employee ID, which you could store and then pass into printEmployee.

Resources