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.
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.
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.
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
.