-5
int n;

scanf("%d",&n); //input from keyboard=5
printf("%d ",n); //gives output 5.

n=scanf("%d",&n); //input from keyboard=5
printf("%d ",n); //gives output 1.

Need help understanding the second one.

Borgleader
  • 15,826
  • 5
  • 46
  • 62

2 Answers2

2

scanf returns the number of fields it assigns. So, first, it assigns n as 5. Then it returns 1 as it has assigned to only 1 variable. Then, n takes that value.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

That's not the correct way to use scanf(). In C standards scanf() always returns the number of conversion it did from stdin, in your case only 1 conversion is done, hence 1 is assigned to n.

In C, if you want to modify a parameter's value inside a function, you need to pass the address of the variable (&var) to that function, and the parameter of the function should be a pointer (type *). Then, you need to de-reference the pointer like (*ptr).

Now, we need to change the value of n inside scanf() function, that's why we need to give the address of n.

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
  • it's not pass-by-reference because there's no reference in C. C only has pass-by-value and this is passing the pointer value to the function – phuclv Apr 12 '22 at 03:18
  • 1
    @phuclv From a caller point-of-view, arrays are passed by reference. – chux - Reinstate Monica Apr 12 '22 at 03:20
  • @Darth-CodeX since when is IBM docs the authoritarian document? Did you read the C standard? [Does C even have "pass by reference"?](https://stackoverflow.com/q/17168623/995714). Passing the pointer then dereference it manually is no way "pass by reference" where everything is dereferenced automatically – phuclv Apr 12 '22 at 04:25