0

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?

  • 4
    *initialized to 0* No. Local variables are not initialized. – Gerhardh Jun 29 '22 at 11:35
  • 2
    Please don't do that `scanf("\n"); // consume trailing newline` see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) Far better – *essential* – to understand how various `scanf` format specs handle whitespace, both in the format string and in the input stream. – Weather Vane Jun 29 '22 at 11:37
  • 1
    C is no scripting language. You don't need variable names any more after the compiler and linker are done. – Gerhardh Jun 29 '22 at 11:39

1 Answers1

5

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.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312