Home > Net >  in C addresses do not work in functions , why is that?
in C addresses do not work in functions , why is that?

Time:01-17

When trying to use a C style in C:

void square(int &x){
    x = x * x;
};

This gets an error. error: expected ';', ',' or ')' before '&' token

i'm most comfortable with c , but i'm learning C, is there a way to to have adressess in void functions

Tried switching from void -> int, double, char. It only works when i take away the & symbol, but i would like to have an address there. Is there a way to do that? Should i just use * instead of &, like this :

void square(int *x){
    x = (*x) * (*x);
};

CodePudding user response:

C language does not have C references. You need to use pointers

void square(int *x)
{
    *x = *x * *x;
}

Your second code is invalid as you assign a local pointer with integer converted to pointer.

CodePudding user response:

Even in C the sign & does not denote an address in a declaration. It denotes a reference.

This declaration in C

void square(int &x){
//...
}

means that the function accepts its argiment by reference.

In C passing by reference means passing an object indirectly through a pointer to it. So dereferencing a pointer within a function you get a direct access to the original object passed to the function through the pointer.

So this function in C

void square(int &x){
    x = x * x;
}

accepts an object of the type int by reference.

In C this function

void square(int *x){
    *x = *x * *x;
}

accepts an object of the type int by reference indirectly through a pointer to it.

Pay attention to that the assignment statement in the second function

void square(int *x){
    x = (*x) * (*x);
}

is incorrect. You are trying to assign an integer expression to a pointer. You have to write

    *x = *x * *x;

as already shown above. That is you need to change the passed object of the type int to the function indirectly through a pointer to it.

  • Related