Home > other >  Does C has pass by reference?
Does C has pass by reference?

Time:11-20

I have this function here that my compiler is complaining. It keeps saying that is missing parenthesis which is not. If I remove the ampersand then the compiler stops complaining. So my question is. Does C support ampersand? Should I use a pointer instead? so change int &cnt to int *cnt?

int counter (int in, int &cnt, int &en)
{
    static int in_old = 0;

    if (in_old == 0)
        if (in > 10)
            cnt = cnt   1;
    if (cnt > 1)
        en = 1;

    in_old = in;
    // write counter code here

    return 0;

}



CodePudding user response:

C does not have references.
This code must come from C !

Note however, that C does use the ampersand operator to obtain the address of a variable.

So if you change your function to accept pointers, you could do something like this:

int counter (int in, int *cnt, int *en);

int main(int argc, char **argv) {
    int the_cnt = 1;
    int the_en = 2;
    int in = 3;

    int res = counter(in, &cnt, &en);

    ...
}

You will also have to dereference the pointers in the function:

int counter (int in, int *cnt, int *en)
{
    static int in_old = 0;

    if (in_old == 0)
        if (in > 10)
            *cnt = *cnt   1;
    if (*cnt > 1)
        *en = 1;

    in_old = in;
    // write counter code here

    return 0;

}
  •  Tags:  
  • c
  • Related