Home > Software engineering >  f(&a) is possible to run in C?
f(&a) is possible to run in C?

Time:12-19

The explanation below confused me:

When an argument is pointer to a variable x, we normally assume that x will be modified : f(&x);

It is possible, though, that f merely needs to examine the value of x, not change it.

I tired to understand and the code below can't work.

#include <stdio.h>

void function(int& a)
{
    a = 5;
}

void func(int b)
{
    b = 5;
}

int main(void)
{
    int x = 0;

    function(x);
    printf("%d", function(x));

    func(x);
    printf("%d", func(x));

    return 0;
}

Code refer from the second answer:

int f(int &a){
  a = 5;
}
int x = 0;
f(x);
//now x equals 5

int f2(int b){
 b = 5;
}
int y = 0;
f2(y);
//y still equals 0

CodePudding user response:

An example actually using f(&x):

#include <stdio.h>

void f(int *p) {
   *p = 4;
}

int main(void) {
   int x;
   f(&x);               // Provide a pointer to `x`.
   printf("%d\n", x);   // 4
   return 0;
}

Both of your program use int &a, which isn't a valid C declaration. That is why they don't even compile.

  • Related