Error in passing value of local variable in other function - c

I am making a program in C in which I am trying to use the values of local variable in other function. Lets say I have two function foo1 foo2.
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
int foo2(int c)
{
printf("Value of C is %d",c);
}
is this method correct, if not what else is the way to use values of local variable in other function?

first of all, this two functions foo1() and foo2() are not related...
and local variables have block scope only.
If you want to use them in other functions make them global or use pass by value and pass by reference methods to pass the variables from one function to others...

You cannot, and you should not use local variables from other functions directly.
But in your case you are lucky: the value from foo1() you are interested in is returned to the caller.
This way you can use it as you like:
...
int value = foo1();
foo2(value);
...
or even shorter:
...
foo2(foo1());
...

You can do this -
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
// c will be passed to the function and printed
int foo2(c)
{
printf("Value of C is %d",c);
}
// get the result of foo1()
int val = foo1();
// call foo2() with the result of foo1()
foo2(val);

One way is to make c variable global so that every function can use it.
other way is to call this returning function in foo2() so that the returned value can be printed.
one way:
int foo1(){
int a=2,int b=3;
int c=a+b;
return c;
}
int foo2(){
printf("value of c = %d",foo1()); //returned value of function foo1() used
}
other way is :
int c=0; //defined global
void foo1()
{
int a=2,int b=3;
c=a+b;
}
void foo2()
{
printf("value of c = %d",c);
}

Related

I can change the pointer's function?

In script languages, such as Perl and Python, I can change function in run-time. I can do something in C by changing the pointer to a function?
Something like:
void fun1() {
printf("fun1\n");
}
void fun2() {
printf("fun2\n");
}
int main() {
fun1 = &fun2;
fun1(); // print "fun2"
return 0;
}
No. You can't do that.
You can regard fun1 as a placeholder for the fixed entry point of that function.
The semantic you are looking for is that from fun1=&fun2; point on every call to fun1 causes fun2 to be called.
fun1 is a value not a variable. In the same way in the statement int x=1; x is a variable and 1 is a value.
Your code makes no more sense than thinking 1=2; will compile and from that point on x=x+1; will result in x being incremented by 2.
Just because fun1 is an identifier doesn't mean it's a variable let alone assignable.
Yes; You can and this is the simple program which will help you in understanding this
#include <stdio.h>
void fun1() {
printf("fun1\n");
}
void fun2() {
printf("fun2\n");
}
int main() {
void (*fun)() = &fun1;
fun(); // print "fun1"
fun = &fun2;
fun(); // print "fun2"
return 0;
}
Output
➤ ./a.exe
fun1
fun2
You can't change fun1, but you can declare a function pointer (not a function, only a pointer to a function).
void (*fun)();
fun = fun1;
fun(); /* calls fun1 */
fun = fun2;
fun(); /* calls fun2 */
As you might have noticed it is not necessary to take the address of fun1/fun2 explicitely, you can omit the address-of operator '&'.

How to update a variable using a function with no arguments and no return type in C

I know that If a function has no argument & only return type (say int), then I can change my int variable by assigning the function to my variable as below,
main()
{
int var_name;
var_name = func();
printf("My variable value is updated as : %d", a);
}
func()
{ return 100; }
Also I know that If I have my function's return type as void, with no arguments, then I can only print the value inside the function itself and cannot return anything in turn.
But, my doubt is, is there anything else that I can do to update my var_name by calling a function with no arguments & no return type ?
ie., void func(void); by using something like pointer concepts ??
I could not able to find the exact answer for the same by my searches among so many websites.. I will be very grateful if someone can help me out finding whether I can do it by this way or not,.
Thanks,.
It is possible to modify a local variable in main, from a function with no arguments and no return value, if there's a global pointer to it:
#include <stdio.h>
int *p;
void func() {
*p = 6;
}
int main() {
int a = 5;
p = &a;
func();
printf("a = %d\n", a); // prints: a = 6
return 0;
}
There's no good way to do that. If you want the function to modify a local variable, you should probably change the function so it either returns a value that you can assign to the variable, or takes the variable's address as an argument.
But if you don't mind writing some ugly code, you can define a global (file-scope) pointer variable, assign the local variable's address to the global pointer, and then use that to modify the variable inside the function.
An example:
#include <stdio.h>
int *global_pointer;
void func(void) {
*global_pointer = 42;
}
int main(void) {
int local_variable = 0;
global_pointer = &local_variable;
func();
printf("local_variable = %d\n", local_variable);
}
It's very easy to shoot yourself in the foot his way. For example, if you refer to the pointer after the calling function has terminated (and the local variable no longer exists), you'll have undefined behavior.
This technique can actually be useful if you need to make a quick temporary change in a body of code in which you can't make major interface changes. Just don't do it in code that will be maintained by anyone else -- and wash your hands afterward.
You can have global variable
int var_name;
void func();
int main()
{
func();
printf("%d\n",var_name);
}
void func()
{
var_name = 20;
}
But if your variable is local to main() then this can't be done.
There are two ways to modify the value of var_name.
Make changes in the calling function and return the value.( which you have already shown)
Pass the address of the var_name to the function and have pointer as arguement in the func(int *p) and modify the value inside the func()
Thats it!! No other way this can be done.

Cannot get function in C to execute properly

I have a simple function that I am trying to create. I need this function to add 6 to whatever number the user decides to enter into the program. I have been working with this code for an hour now and cannot figure out what I'm doing wrong, even after looking at multiple examples from the course I am taking. I really appreciate the help.
Here is my code:
#include <stdio.h>
void closing(void);
void addSix(void);
int x;
int result;
int main()
{
int x;
printf("Please enter a number to add to 6: ");
scanf("%d", &x);
getchar();
addSix();
closing();
closing();
return 0;
}
void closing(void)
{
printf("That's all folks.\n");
}
void addSix(void)
{
int result = x+6;
printf("Result: %d\n", result);
}
You've got both a global x variable outside of main(), and a local x inside of main(). The code inside of main() writes to the local x while the code in addSix() reads from the global x.
Remove the int x declaration in main() so that both places access the global x.
You have x declared as both a global variable and variable local to main. When you pass x by pointer to scanf, it refers to the local variable, not the global.
You can remove the local declaration of int x in main but this isn't really the best solution. Generally, global variables should be avoided when possible (though they are, of course, sometimes necessary/the best tool for the job).
The best solution in this case is to make x a parameter to addSix(). There are a few options here:
You can have addSix return the sum and then use that return value
You can pass the address of x to addSix and have the function modify x itself by using a pointer.
The former would look like this:
int addSix(int x) {
return x + 6;
}
The latter would look like this:
void addSix(int * x) {
*x += 6;
}
You have two variables named x. One is a local to main, and the other is a global variable.
The function addSix cannot see the local in main. It can only see the global variable.
You should change addSix so that it is passed the value as a parameter.
void addSix(int x)
{
printf("Result: %d\n", x+6);
}
Call the function like this:
addSix(x);
Or perhaps you want your function to return a value:
int addSix(int x)
{
return x+6;
}
Which you can call like this:
int result = addSix(x);
Both of your global variables are needless. Remove them.
You have a global x, and a local x variable in which you actually save the user input.
Using only the global variable will do the trick for you
#include <stdio.h>
int x;
void addSix(void)
{
int result = x+6;
printf("Result: %d\n", result);
}
int main()
{
printf("Please enter a number to add to 6: ");
scanf("%d", &x);
getchar();
addSix();
return 0;
}

How to share a variable between two functions in C?

In C, suppose var1 is a variable in foo1() and foo2() wants to access var1, however, foo1() doesn't call foo2(), so we can't pass it by parameter. At the same time, only foo1() and foo2() will access it, so I wouldn't like to declare it as global variable. It will be similar with the "friend semantics" in c++, is there any way to implement this in C?
void foo1() {
...
var1;
....
}
void foo2() {
...
how to access var1?
...
}
you pass the variable to both functions.... in general functions shouldn't hold state.
quickly you find passing variables is not so nice and becomes fragile, so instead, you pass structs.... then functions start working on the state of structs.
typedef struct
{
int var1;
} blah_t;
void foo1(blah_t* b)
{
b->var1=0;
}
void foo2(blah_t* b)
{
b->var1++;
}
this is the very simplistic seed idea behind doing OO C.
You need to declare var1 outside the scope of the functions and then send it as a parameter to both. Alternatively, declare it as a global variable.
by reference is one way: (in this example the memory for i is local to caller())
void caller()
{
int i = 5;
foo(&i);
bar(&i);
printf("\n final i is %d",i);
}
void foo(int *i)
{
printf("%d",*i);
*i += 5;
}
void bar (int *i)
{
printf("%d",*i);
*i += 5;
}
global: (usually considered horrible i would have a name more like GLOBAL_I or something)
int i = 0;
void caller()
{
i=5;
foo();
bar();
printf("\n final i is %d",i);
}
void foo()
{
printf("%d",i);
i += 5;
}
void bar (int i)
{
printf("%d",i);
i += 5;
}
Regarding similar with the "friend semantics" in c++. C does not have the same capability.
Regarding so we can't pass it by parameter
The only option in C for accessing a variable from function to function without passing as a function parameter is to use some type of global scope variable.
In the event void foo1() and void foo2() exist in different C modules...
but you still want to be able to access the same variable, and ensure its value is the same at all times, in all places within your project, then consider using extern scope:
Within a header file that is common to both (multiple) modules, a project scope global can be implemented as follows.
file.h
void foo1(void);
void foo2(void);
extern int var1;
file1.c
#include "file.h"
int var1 = 5; //in only 1 module, declare and initialize the
//extern defined in the common header -file.h-
int main(void)
{
printf("value of var1 is %d\n", var1);//original value of var1
foo1();
printf("value of var1 is %d\n", var1);//var1 modified by foo1()
foo2();
printf("value of var1 is %d\n", var1);//var1 modified by foo2()
return 0;
}
void foo1(void)
{
var1 = 15;//Now that the project global variable
//has already been declared and defined, it can simply
//be used, in this file...
}
file2.c
#include "file.h"
void foo2(void)
{
var1 = 20;... and in this one
}
No. The variable only exists on the function stack while foo1() is running. The stack will vanish when leaving the function. You could make the variable static to keep it alive, but then you can't access it from the outside either without hacks.
This answer is inspired by the 'Module' concept, found in many other languages, which can be approximated using gcc's nested functions. Variable var1 is within scope for both foo1() and foo2(), but is out of scope for everything else. The solution uses neither global vars nor parameters.
void foo(int fn)
{
static int var1;
void fn1(void)
{
var1 = 15;
}
void fn2(void)
{
var1 = 20;
}
(fn == 1)? fn1(): fn2();
printf("Value of var1 is now %d\n", var1);
}
void foo1(void){foo(1);}
void foo2(void){foo(2);}
int main (void)
{
foo1();
// Expected stdout: Value of var1 is now 15
foo2();
// Expected stdout: Value of var1 is now 20
}

How can I call a function using a function pointer?

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!

Resources