1

Possible Duplicate:
Why scanf must take the address of operator

Why do we pass the variable in the case of printf(), whereas the address of the variable in the case of scanf()? why to pass address in scanf

Cœur
  • 37,241
  • 25
  • 195
  • 267
minefield
  • 41
  • 4

2 Answers2

4

why to use '&' in scanf( ) but not in printf( )

'printf'()' only need the values in order to output them. 'scanf()' stores values, so it needs a place to store them. This is done by providing the addresses (in pointers) of where to store the values.

Jacob Seleznev
  • 8,013
  • 3
  • 24
  • 34
2

With scanf you want the callee to modify the variable that's why you pass it by reference, if you pass it by value like with scanf you would not have access to the variables address to modify its contents.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • scanf needs a pointer not a reference – Adrian Cornish Aug 24 '12 at 03:29
  • @AdrianCornish, References in the C++ sense don't exist in C. – chris Aug 24 '12 at 03:29
  • @Chris I know - my point exactly :-) – Adrian Cornish Aug 24 '12 at 03:30
  • @AdrianCornish, A reference can mean passing by pointer, but in C++, it has evolved into a more specific concept than what by pointer and by reference are both in the same boat of. – chris Aug 24 '12 at 03:31
  • @Chris My comment is against the statement made by Musa "that's why you pass it by reference" Which is why it is not a reference as scanf is a C library function - Please read more carefully – Adrian Cornish Aug 24 '12 at 03:33
  • 3
    In C, 'pass by reference' means 'pass the address of the object'. Since the question is not tagged C++, it does _not_ matter what C++ calls a reference (or what C++ means by 'reference'). The term 'pass by reference' predates C++. – Jonathan Leffler Aug 24 '12 at 03:33
  • @JonathanLeffler Does C99 use the word reference in this context? Does C++ 14882 or C++14882-2011 - yes they do. In this case the word reference if defined. – Adrian Cornish Aug 24 '12 at 03:39
  • 1
    C does not define the word "reference". Here it's used purely in the English sense. The same way you could use it when talking about a C program performing reference counting. It's perfectly reasonable usage; the fact that "reference" is a specifically-defined technical term in another language is irrelevant. – R.. GitHub STOP HELPING ICE Aug 24 '12 at 05:26