Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a variable in a calling function from a called function? [duplicate]

Tags:

c

How should the try() function be modified (and it's call) to get the output as 11 from the program below?

#include <stdio.h>

/* declare try() here */

int main(void)
{
    int x = 10;
    try();              /* Call can change */
    printf("%d\n", x);
    return 0;
}

void try()              /* Signature can change */
{
    /* how to change x here?? */
}
like image 472
kaka Avatar asked Jul 31 '10 06:07

kaka


People also ask

Can functions directly alter a variable in the calling function?

Any variable changes made within a function are local to that function. A calling function's variables are not affected by the actions of a called function.

Can a function change a variable?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).

How do you change a variable inside a function in Python?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.


2 Answers

To change the value of x from within a function, have try() take a pointer to the variable and change it there.

e.g.,

void try(int *x)
{
    *x = 11;
}

int main()
{
    int x = 10;
    try(&x);
    printf("%d",x);
    return 0;
}
like image 100
Jeff Mercado Avatar answered Jan 04 '23 11:01

Jeff Mercado


The other answers are correct. The only way to truly change a variable inside another function is to pass it via pointer. Jeff M's example is the best, here.

If it doesn't really have to be that exact same variable, you can return the value from that function, and re-assign it to the variable, ala:

int try(int x)
{
  x = x + 1;
  return x;
}

int main()
{
  int x = 10;
  x = try(x);
  printf("%d",x);
  return 0;
}

Another option is to make it global (but don't do this very often - it is extremely messy!):

int x;

void try()
{
  x = 5;
}

int main()
{
  x = 10;
  try();
  printf("%d",x);
  return 0;
}
like image 40
Merlyn Morgan-Graham Avatar answered Jan 04 '23 12:01

Merlyn Morgan-Graham