0

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 ?

1
  • 9
    Because C passes arguments by copy, without using pointer it cannot modify an object. Commented Jun 22, 2013 at 12:32

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I got your point and appreciate your response. But my question is why to take memory location instead of variable name. 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 ?
@user2511623 C++ introduced references, which (to put it very crudely) are just syntax sugar for pointers. The underlying principle with references (what cin>> uses) is exactly the same as with pointers (what scanf uses). C did not have references, so the only option was pointers.
Thanks tom. Is it one of the reason that makes c is faster than c++ and others?
@Harikesh No. Modern optimizing compilers are extremely complicated and speculations on what would be faster and why are useless.
1

You need to pass the variable by reference to scanf() so that the scanf() can write the data at that address..

1 Comment

-1, scanf() certainly doesn't "write the address to the provided pointer".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.