-1

why we use & (ampersn) sign in scanf() while storing value.

PS : I know it is used to store value of variable at proper address.

Is there any other proper reason?

coDe murDerer
  • 1,858
  • 4
  • 20
  • 28
Ankita Mehta
  • 442
  • 3
  • 16

2 Answers2

3

In C you can only pass arguments by value. That means as you pass an argument to a function, the value is copied.

C doesn't have pass by reference, but it can be emulated using pointers.

For example

#include <stdio.h>

void f1(int a)
{
    a = 123;  // Modify local copy
}

void f2(int *a)
{
    *a = 234;  // Modify value where a is pointing
}

int main(void)
{
    int a1 = 0, a2 = 0;

    f1(a1);
    f2(&a2);

    printf("a1 = %d, a2 = %d\n", a1, a2);
}

The above program would print

a1 = 0, a2 = 234

That's because when f1 modifies the value of its argument, it only modifies its local copy. The original (the variable a1 in the main function) is not modified.

The function f2 on the other hand emulates pass by reference. When calling f2 we pass a pointer to the variable a2 by using the address-of operator &. Then the function can dereference that pointer to get where it is pointing (the variable a2 in the main function) and modify it.

Because the scanf function needs to modify variables, you can not pass copies of their current values, you need to pass pointers to the variables like when calling f2 in the above example.

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

In c all function parameters are passed by value.

That means that a function cannot modify the parameters passed by the caller.

What it can do, other than making use of return, is to accept pointer types (to arrays or objects) as parameters, and modify those arrays or objects by dereferencing those pointers.

This is the approach used by scanf. scanf also makes use of return as well.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483