Xavier99
Xavier99

Reputation: 15

Calling function to add one to a number in C

Here is what I am trying to do:

-Have a variable call_count, an integer initialized to zero

-Call functions f1 and f2 several times

-Output the final value of call_count

-Two functions, f1, and f2 that when called cause call_count to increment by 1

This is what I could do so far but when I compile and run this, it still outputs 0. What am I doing wrong? Thanks for the help.

Question edit: How can I use a pointer here to accomplish this?

#include <stdio.h>

void f1(int call_count){ call_count = call_count + 1;}
void f2(int call_count){ call_count = call_count + 1;}

int main(){

    int call_count = 0;
    f1(call_count);
    f2(call_count);

    printf("%d",call_count);
    }

Upvotes: 0

Views: 516

Answers (2)

hanie
hanie

Reputation: 1885

you are sending a copy of call_count to functions f1 and f2 , in C by default called by value method will be used.

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

you have to way to do what you want :

  1. you can return call_count.

  2. using pointers which means call by reference.

since you want to use pointers to accomplish this:

void f1(int *call_count) { *call_count = *call_count + 1; }
void f2(int *call_count) { *call_count = *call_count + 1; }

int main() {

    int call_count = 0;
    f1(&call_count);
    f2(&call_count);

    printf("%d", call_count);
}

Upvotes: 1

Joe
Joe

Reputation: 43

Because you lost the value in the memory, you have two solutions : 1 you should use pointer :

int main()
{
 void f1(int*call_count){ *call_count = *call_count + 1;}
void f2(int*call_count){ *call_count = *call_count + 1;}

  int call_count=0;
  f1(&call_count);
  f2(&call_count);

  printf("%d",call_count);

 }

Or you change the function type : int instead of void

int main()
{
 int f1(int call_count){ return call_count + 1;}
 int f2(int call_count){ return  call_count + 1;}

  int call_count=0;
  int result1=f1(call_count);
  int result2=f2(result1);

  printf("%d",result2);

}

If you don't know how pointer works in your case, you have to use the solution 2

Upvotes: 1

Related Questions