Why use symbol & when using scanf in C?

  • Thread starter Thread starter jd12345
  • Start date Start date
  • Tags Tags
    Symbol
AI Thread Summary
The use of the ampersand "&" in the scanf function in C is essential because it provides the address of the variable where the input value will be stored. Unlike printf, which only requires the value of the variable and does not modify it, scanf needs a pointer to the variable to directly change its value. This distinction is crucial for understanding how data is handled in C, as scanf modifies the variable by writing to its memory address, while printf simply reads and displays the value without altering it. The "&" operator is not merely a convention; it serves a functional purpose in enabling scanf to work correctly.
jd12345
Messages
251
Reaction score
2
Why use symbol "&" when using scanf in C?

When using scanf like in scanf("%d",&x); why do we use '&' before x? can't we write directly ,x as in printf command? Is it just a convention? I think it should have a reason.. they won't just put an "&" just like that
 
Technology news on Phys.org


"&x" means to generate a pointer to "x". Scanf needs a pointer to x in order to store the value and change "x". Printf uses a copy of the value of "x" passed as a parameter (usually on the stack), since it isn't changing the value of "x".
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top