-3

I wrote the same code in PHP, the value of 5 got incremented, but why doesn't the value get incremented in C?

int foo(int x){
   x++;
}

int main( ){
   int y = 5;
   foo(y);  
   printf("value of y = %d\n", y);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
brandoncraig
  • 53
  • 3
  • 10
  • 2
    Possible duplicate of [Update (int) variable in C inside a function](http://stackoverflow.com/questions/23667497/update-int-variable-in-c-inside-a-function) – phuclv Mar 19 '17 at 05:36
  • C is not PHP. There are already tons of questions about this. And not only this, your code suffers from a problem by not returning anything in the function – phuclv Mar 19 '17 at 05:37
  • I tried PHP: https://ideone.com/WNlIIR. The variable is not incremented, the output is `5`, same as C. – melpomene Nov 15 '18 at 09:36

5 Answers5

3

In C passing arguments is done by value rather than by reference. That is, the number that the function is working with is unique to the one passed to and has its own space in memory. To get around this do

int foo(int* x){
   (*x)++;
}

int main( ){
   int y = 5;
   foo(&y);  
   printf("value of y = %d\n", y); 


}
theKunz
  • 444
  • 4
  • 12
2

You should pass the parameter by reference to function foo.

int foo(int *x){
   (*x)++;
}

int main( ){
   int y = 5;
   foo(&y);  
   printf("value of y = %d\n", y); 
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user7676575
  • 141
  • 6
1

Because x, y are local variables to their functions. The scope of the variable lies within the block of the function. So you can't change the value of those variables from outside the block.

Solution: Either you declare those variables as global variables

int y;
int foo(){
   y++;
}
int main( ){
  y = 5;
  foo();  
  printf("value of y = %d\n", y); 
}

Or using reference you can do that

int foo(int *x){
    (*x)++;
}

int main( ){
    int y = 5;
    foo(&y);  
    printf("value of y = %d\n", y); 
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
1

Might be in PHP it is directly pass-by-reference. But C has different function calls. If you want to increment the value in the function and it should reflect in the main function. There are two possible ways :

1.

int foo(int x)
{
   return ++x; //returning the incremented value
}

2.

void foo(int *x)
{
    ++(*x);//this function is pass-by-reference.
}

Please let me know if there are any issue.

  • It does work. There should be a variable that should store the return value of the foo function or the function can be called from the print function where it directly displays the incremented value. – Susarla Nikhilesh Mar 20 '17 at 10:23
0

What you could also be doing if you want to avoid using pointers is as below

int addone(int n);
int main(void) {

    int n=0;
    printf("Before: %d\n", n);

    n=addone(n);//assign the returned  value from function to the variable 'n'

    printf("After: %d\n", n);

    return 0;
}

int addone(int n) {
    n++;
    return n;
}