0

Just started C this year in my uni and I'm confused whether my function call is by reference or value.

I created an empty array in main called freq_array and this is passed as an argument when the function frequency is called. So since after the func call, the empty array will now contain values, this is considered call by reference? I read in other websites that call by reference uses pointers so I'm slightly confused. Thank you.

 void frequency(int[]);    //prototype

 frequency(freq_array); //func call

 void frequency(int fr[arraysize]) //arraysize = 18
 {
       int n;

       for (n=0; n<10; n++)
       {
        fr[n]= 100 * (n + 1);   //goes from 100Hz - 1000Hz
       }

        for (n=10; n<18; n++)       //goes from 2000Hz - 9000Hz
       {
         fr[n]= 1000 * (n - 8); 
       }

     }
QQQ
  • 97
  • 7

2 Answers2

4

In theory, C only has "pass by value". However, when you use an array as parameter to a function, it gets adjusted ("decays") into a pointer to the first element.

Therefore void frequency(int fr[arraysize]) is completely equivalent to void frequency(int* fr). The compiler will replace the former with the latter "behind the lines".

So you can regard this as the array getting passed by reference, but the pointer itself, pointing at the first element, getting passed by value.

Lundin
  • 195,001
  • 40
  • 254
  • 396
2

For arguments, you can't pass arrays only pointers. When the compiler sees the argument int fr[arraysize] it will treat is as int *fr.

When you do the call

frequency(freq_array);

the array decays to a pointer to its first element. The above call is equal to

frequency(&freq_array[0]);

And C doesn't have pass by reference at all. The pointer will be passed by value.

However using pointers you can emulate pass by reference. For example

void emulate_pass_by_reference(int *a)
{
    *a = 10;  // Use dereference to access the memory that the pointer a is pointing to
}

int main(void)
{
    int b = 5;

    printf("Before call: b = %d\n", b);  // Will print that b is 5

    emulate_pass_by_reference(&b);  // Pass a pointer to the variable b

    printf("After call: b = %d\n", b);  // Will print that b is 10
}

Now, it's important to know that the pointer itself (&b) will be passed by value.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621