Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does scanf store value?

I’m new to C. Given the following code,

int main(void)
{
 int a;
 scanf("%d",&a);
 scanf("\n"); // consume trailing newline
}

As I understand it, the first declaration statement tells the compiler to allocate memory for an integer type variable with an identifier ‘a’ initialized to 0(as ‘a==0’). Scanf needs a valid memory address to store the user input(say 5) so &a being the memory address of ‘a’ is where the user input is stored as ‘a==5’. Is this the case or ‘a’ is stored as a variable name for the memory address and the contents of the address are simply 5?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is this the case or ‘a’ is stored as a variable name for the memory address

&a is a pointer to the memory reserved for a. The name “a” is not involved.

… initialized to 0

Automatic objects are not initialized by default. Any object declared inside a function without static, extern, or _Thread_local has automatic storage duration.

The value of an uninitialized object is indeterminate, meaning it has no fixed value; it may behave as if it has a different value each time it is used. (If you explicitly initialize any part of an automatic object, such as one element of an array or one member of a structure, the entire object will be initialized, defaulting to zeros for numeric types and null pointers for pointer types.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading