Is there any particular reason why while taking input C (scanf) prefers to take memory location of variable instead of the name of variable itself ? I know its definition of scanf which mandates above ? But is there any special reason ? Like in c++ if u want to take input you'll write cin>>var; But why not in ? Is it something to keep language faster ?
2 Answers
It's because values to functions in C are passed by value. And, of course, being a compiled language names of variables don't exist at run-time, it's all addresses in memory at that point.
If you pass the variable directly, you just pass the value, which is what printf() needs:
int a = 32;
printf("a=%d\n", a);
but if you did the same with scanf()', it would just get the integer value32, with no idea where it came from. Since the point ofscanf()` is to change the value of the caller's variable, you pass the address of the variable:
int a = 32;
scanf("%d", &a);
Then the code inside scanf() can write a new integer value at the given address, which causes the value to change in a.
4 Comments
cin>> uses) is exactly the same as with pointers (what scanf uses). C did not have references, so the only option was pointers.You need to pass the variable by reference to scanf() so that the scanf() can write the data at that address..
1 Comment
scanf() certainly doesn't "write the address to the provided pointer".