In the mentioned code, how to get the updated value in the statement of printf("value : %d\n",a);
#include <stdio.h>
#include <stdbool.h>
#define TRUE 1;
#define FALSE 0;
void printbool(bool a);
int main()
{
bool a = FALSE;
printf("Hello, World!\n");
printbool(a);
printf("value : %d\n",a);
return 0;
}
void printbool(bool a)
{
a = TRUE;
}
Try this:
void printbool(bool *a)
{
*a = TRUE;
}
In main, call function like this: printbool(&a);
C uses pass-by value for function argument passing, thereby changes made to a received parameter inside the function will not reflect to the caller.
You can either
return the new value and store into the original variable
bool changebool(bool a)
{
a = TRUE;
return a;
}
and, in main()
a = changebool(a);
pass a pointer to the original variable and make change to the value at the address pointer is pointing to.
void changebool(bool* a)
{
*a = TRUE;
}
and, in main()
changebool(&a);
Note:
Get rid of the ;s in the #define, they are not needed and likely to cause problems later on.
stdbool.h already defines true and false, you can make use of them instead trying to define your own constants.
In approach 1, we need to change the return type of the function.
Please use a meaningful name to functions, not to confuse the future readers (including yourself). I already did to my example.
You need to pass a pointer and then dereference inside the function in order to change/alter the passed argument:
#include <stdio.h>
#include <stdbool.h>
#define TRUE 1
#define FALSE 0
void printbool(bool *a);
int main()
{
bool a = FALSE;
printf("Hello, World!\n");
printbool(&a);
printf("value : %d\n",a);
return 0;
}
void printbool(bool *a)
{
*a = TRUE;
}
Also notice that you don't need to define TRUE and FALSE if you are including stdbool.h, instead use true and false.
void printbool(bool a)
needs to be
void printbool(bool *a)
and assign through the pointer:
*a=TRUE;
call as
printbool(&a);
Basic stuff - you need to know this.
I have a problem in C. I have this function :
int test(void *data);
I want to change data with this function but I don't want another prototype (not use void **). Actualy, data equals null out this function.
#include <stdio.h>
#include <stdlib.h>
int
test(void *data)
{
data = "toto";
return 1;
}
int
main()
{
void *d;
if (test(d) != 1) {
printf("erreur\n");
}
printf("résultat : %s\n", (char *) d); // displays "résultat : (null)"
return 0;
}
Help me please. ;)
In C arguments to function are passed by value. d is passed by value to function test. data is a local variable to function test and d is copied to data. The assignment
data = "toto";
makes pointer data to point to string literal toto, while d is unaffected of this assignment in main function. So, this assignment has no effect on d.
In main you are dereferencing an uninitialized pointer. This will result in undefined behavior.
In your test function, you change data, which doesn't affect d because data is just a local variable. If you really need to change d, then you need to let test return data and do d=test(d).
Moreover, in your test function, the value of data is never used. So what is the point to have data as a parameter of the function?
In printf("résultat : %s\n", (char *) d);, you try to cast d into pointer to char and then print the value of d. Although you don't dereference d, you are still printing a variable that hasn't been initialized, which is undefined behavior.
Any object pointer (i.e. non-function pointer) can be converted to a void * and back to the original type without altering the value. This means that you can pass any kind of (object) pointer to your test() function, it will be automatically converted to a void *, and you can then convert it back inside test().
#include <stdio.h>
int test(void *data)
{
char **s = data;
*s = "toto";
return 1;
}
int main()
{
char *res;
if (test(&res) != 1) {
printf("erreur\n");
}
printf("résultat : %s\n", res);
return 0;
}
You just need to make sure that the test() function knows what the original type was.
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
Can someone explain why the value of the variable test isn't changed when I run the short code snippet below?
#include <stdio.h>
int f1(char * foo) {
*foo = 'a';
return 0;
}
void main(void) {
char test = 'n';
printf("f1(&test)=%d. test's new value? : %c", f1(&test), test);
}
I know I'm probably missing something really simple. I just don't understand why test isn't changed in f1() because I'm passing it's address in, right? Why does it matter that the actual function call happens in the list of arguments to printf() ?
If I take the call to f1() out of the printf argument list like so:
#include <stdio.h>
int f1(char * foo) {
*foo = 'a';
return 0;
}
void main(void) {
char test='n';
int i;
i = f1(&test);
printf("f1(&test)=%d. test's new value? : %c", i, test);
}
things work as expected.
thanks in advance.
The order in which the arguments to a function call are evaluated is unspecified. Put another way, you can't tell for sure when f1(&test) will be evaluated.
So in your example, perhaps f1(&test) is evaluated after test: slightly counter-intuitively, you don't get to see the side effects of that invocation. But if you print test again after the call, you will indeed see them.
Bottom line, just be careful with function that have side-effects and you should be set.
There is no set order in which function parameters are evaluated. You're banking on the idea that the arguments are evaluated left to right, which can't be assumed.
Just change where you make your function call
#include <stdio.h>
int f1 (char* foo) {
*foo='a';
return 0;
}
int main(void)
{
char test='n';
f1(&test);
printf("test=%c\n", test);
return 0;
}
Suppose I have these three functions:
bool A();
bool B();
bool C();
How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?
You can do the following:
Suppose you have your A,B & C function as the following:
bool A()
{
.....
}
bool B()
{
.....
}
bool C()
{
.....
}
Now at some other function, say at main:
int main()
{
bool (*choice) ();
// now if there is if-else statement for making "choice" to
// point at a particular function then proceed as following
if ( x == 1 )
choice = A;
else if ( x == 2 )
choice = B;
else
choice = C;
if(choice())
printf("Success\n");
else
printf("Failure\n");
.........
.........
}
Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.
I think your question has already been answered more than adequately, but it might be useful to point out explicitly that given a function pointer
void (*pf)(int foo, int bar);
the two calls
pf(1, 0);
(*pf)(1, 0);
are exactly equivalent in every way by definition. The choice of which to use is up to you, although it's a good idea to be consistent. For a long time, I preferred (*pf)(1, 0) because it seemed to me that it better reflected the type of pf, however in the last few years I've switched to pf(1, 0).
Declare your function pointer like this:
bool (*f)();
f = A;
f();
Initially define a function pointer array which takes a void and returns a void.
Assuming that your function is taking a void and returning a void.
typedef void (*func_ptr)(void);
Now you can use this to create function pointer variables of such functions.
Like below:
func_ptr array_of_fun_ptr[3];
Now store the address of your functions in the three variables.
array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;
Now you can call these functions using function pointers as below:
some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();
bool (*FuncPtr)()
FuncPtr = A;
FuncPtr();
If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.
You can declare the function pointer as follows:
bool (funptr*)();
Which says we are declaring a function pointer to a function which does not take anything and return a bool.
Next assignment:
funptr = A;
To call the function using the function pointer:
funptr();
Note that when you say:
bool (*a)();
you are declaring a of type "pointer to function returning bool and taking an unspecified number of parameters". Assuming bool is defined (maybe you're using C99 and have included stdbool.h, or it may be a typedef), this may or may not be what you want.
The problem here is that there is no way for the compiler to now check if a is assigned to a correct value. The same problem exists with your function declarations. A(), B(), and C() are all declared as functions "returning bool and taking an unspecified number of parameters".
To see the kind of problems that may have, let's write a program:
#include <stdio.h>
int test_zero(void)
{
return 42;
}
static int test_one(char *data)
{
return printf("%s\n", data);
}
int main(void)
{
/* a is of type "pointer to function returning int
and taking unspecified number of parameters */
int (*a)();
/* b is of type "pointer to function returning int
and taking no parameters */
int (*b)(void);
/* This is OK */
a = test_zero;
printf("a: %d\n", a());
a = test_one; /* OK, since compiler doesn't check the parameters */
printf("a: %d\n", a()); /* oops, wrong number of args */
/* This is OK too */
b = test_zero;
printf("b: %d\n", b());
/* The compiler now does type checking, and sees that the
assignment is wrong, so it can warn us */
b = test_one;
printf("b: %d\n", b()); /* Wrong again */
return 0;
}
When I compile the above with gcc, it says:
warning: assignment from incompatible pointer type
for the line b = test_one;, which is good. There is no warning for the corresponding assignment to a.
So, you should declare your functions as:
bool A(void);
bool B(void);
bool C(void);
And then the variable to hold the function should be declared as:
bool (*choice)(void);
bool (*fptr)();
int main(void)
{
...
...
printf("Enter your choice");
scanf("%d",&a);
switch(a)
{
case 0:
fptr = A;
break;
case 1:
fptr = B;
break;
case 2:
fptr = C;
break;
case 3:
break;
}
(*fptr)();
return 0;
}
Your choice is stored in a. Then accordingly, functions are assigned in the function pointer. Finally, depending on your choice, the very same function is called to return the desired result.
The best way to read that is the clockwise/spiral rule by David Anderson.
Calling a function through a function pointer
float add(int, float), result;
int main()
{
float (*fp)(int, float);
float result;
fp = add;
result = add(5, 10.9); // Normal calling
printf("%f\n\n", result);
result = (*fp)(5, 10.9); // Calling via a function pointer
printf("%f\n\n", result);
result = (fp)(5, 10.9); // Calling via function pointer. The
// indirection operator can be omitted
printf("%f", result);
getch();
}
float add(int a, float b)
{
return a+b;
}
>
Output
15.90000
15.90000
15.90000
You declare a function pointer variable for the given signature of your functions like this:
bool (* fnptr)();
you can assign it one of your functions:
fnptr = A;
and you can call it:
bool result = fnptr();
You might consider using typedefs to define a type for every distinct function signature you need. This will make the code easier to read and to maintain. i.e. for the signature of functions returning bool with no arguments this could be:
typdef bool (* BoolFn)();
and then you can use like this to declare the function pointer variable for this type:
BoolFn fnptr;
Slightly different approach:
bool A() {...}
bool B() {...}
bool C() {...}
int main(void)
{
/**
* Declare an array of pointers to functions returning bool
* and initialize with A, B, and C
*/
bool (*farr[])() = {A, B, C};
...
/**
* Call A, B, or C based on the value of i
* (assumes i is in range of array)
*/
if (farr[i]()) // or (*farr[i])()
{
...
}
...
}
If you need help with complex definitions, like
double (*(*pf)())[3][4];
take a look at my right-left rule here.
//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();
I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..
//assuming bool is available (where I come from it is an enum)
typedef bool (*pmyfun_t)();
pmyfun_t pMyFun;
pMyFun=A; //pMyFun=&A is actually same
pMyFun();
This has been more than adequately answered, but you may find this useful: The Function Pointer Tutorials. It is a truly comprehensive treatment of the subject in five chapters!