Home > Blockchain >  Manipulating Variable Given to Void Function in C
Manipulating Variable Given to Void Function in C

Time:06-12

Is there a way to implement that sort of Code

#include<stdio.h>

void func(int a)
{
    a  ;
}

int main()
{
    int a=0;

    func(a);

    printf("%d", a);

    return 0;
}

The changes I have made to the variable a dont seem to carry over when I reuse it in the main function. I think its done by using static variables but i cant figure out how to do it

CodePudding user response:

you need a 'c style pass by reference'

void func(int *a)
{
    (*a)  ;
}

and

func(&a);

ie - pass in the address of 'a' as a pointer, then update it by dereferencing the pointer

CodePudding user response:

If a is passed by copy (like in this case), changes made by your functions will not affect the variable in your main. You should pass this parameter by reference.

So the solution must be like the following one

#include<stdio.h>

void func(int* a) {
    (*a)  ;
}

int main()
{
    int a=0;
    func(&a);
    printf("%d", a);
    return 0;
}
  • Related