Tametomo
Tametomo

Reputation: 11

The usage of "&" working with printf() and scanf()

I've a simple question concerning the correct usage of "&" before a variable.

printf( "34 * 7 =  " );
scanf( "%d", &x );
printf( "The solution is 238 \n");
printf( "Your solution is %d \n\n", x );

I don't understand why I must use "&x" when reading the user input and why I can go without when using the printf() function. I would like to understand what is behind it.

Upvotes: 1

Views: 193

Answers (4)

Frog
Frog

Reputation: 331

In arguments are always passed by call by value method. So whatever argument you pass a copy is made and stored in the function.

But using pointers, we can make a function 'look-like' implementing a call by reference type of function call!.

For eg:

int fun(int *p)
  {
    p=1;
    return p;
  }

Now take an example of a function call fun(&x);, this function now changes the value of x to 1.

So in case of scanf() there should be an assignment happening inside the function call, and assigning a value to a variable out of scope of the function can only be done by knowing the address the variable(As the name has a scope).

So because of such reasons scanf() funciton is coded keeping in mind that the argument will be an address, so if you pass anything other than an address some of the code will obviously be wrong and thus results in an error.

Upvotes: 0

Vinay
Vinay

Reputation: 188

In printf() function, you are not changing value of variable 'x', whereas in scanf() function you have to change the value of 'x'. '&x' gives the address of x, this is passed to the function scanf(), and the value taken from user is stored in x using the address of x, finally when we return from function scanf() the value of x is stored with the value that user has given. If we do not use '&x', then scanf() function will get a local copy of variable 'x' and the changes will not be reflected when we return from the function.

Upvotes: 1

tommyo
tommyo

Reputation: 551

The scanf function takes a pointer to an int as an argument, in this case, while printf just takes the int. The & is the address-of operator.

Upvotes: 1

Sadique
Sadique

Reputation: 22823

In C, C++, and Go, a prefix "&" is a unary operator denoting the address in memory of the argument, e.g. &x, &func, &a[3].

I don't understand why I must use "&x" when reading the user input

Because that is how the language makers chose to define it. The & operator works fine even without printf and scanf.

int *pointer_to_x = &x;

Now this scanf( "%d", pointer_to_x ); is same as scanf( "%d", &x );

Upvotes: 1

Related Questions