Padhai Search notes and questions

C ProgrammingFrequently askedUnit 9

Differentiate between call by value and call by reference with a suitable example.

5

Answer

In call by value the function receives copies of the arguments, so changes inside the function do not affect the caller. In call by reference the function receives the addresses of the arguments (pointers), so it can change the caller's variables.

Call by value Call by reference
A copy of the value is passed The address is passed
The original variable can't be changed The original variable can be changed
swap(a, b) swap(&a, &b)
#include <stdio.h>
void byValue(int x) { x = 100; }
void byRef(int *x)  { *x = 100; }

int main(void) {
    int a = 5, b = 5;
    byValue(a);   /* a is still 5 */
    byRef(&b);    /* b is now 100 */
    printf("a = %d, b = %d\n", a, b);
    return 0;
}

Output: a = 5, b = 100.

All C Programming old questions