Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use values of local variable in another function in C

Tags:

c

variables

local

Suppose there are two function i.e., function1() and function2()

int function1()
{
  int F;
  printf("enter any value");
  scanf("%d",&F); 
  printf("Value is %d",F);
}

In function1() variable F is used which is local variable. How can I use the value of this local variable F in another function function2()?

like image 975
Aircraft Avatar asked Oct 17 '25 18:10

Aircraft


2 Answers

Actually, you already did.

passing the reference of F to scanf is how to use it. Writing your own function, you only need to decide if you are passing the reference or the value. If passing the value

int function(int value) {
 ...
}

which would be called like

function(F);

if passing the reference

int function(int* value) {
  ...
}

which would be called like

function(&F);
like image 115
Edwin Buck Avatar answered Oct 20 '25 09:10

Edwin Buck


Function local variable lifetimes are local to that function. If you have to use a value held by a local variable inside a function to another function, you can

  1. return the value from function1().
  2. collect the return value in the caller function.
  3. pass the stored value as argument to function2().

NOTE: above answer assumes that both function1() and function2() are called from a parent function, maybe func().


Edit:

if you need to use multiple values of local variables in other functions, (without using global variables), most common practice is to

  1. pass a pointer to structure as argument of the function1()
  2. fill the member element values inside function1() from the local variables.
  3. pass the structure (or, address of the structure, is needed) again to function2() as argument.
like image 22
Sourav Ghosh Avatar answered Oct 20 '25 09:10

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!