How garbage values are assigned to variables in c

后端 未结 4 350
后悔当初
后悔当初 2020-11-29 11:59

C code :

int a;
printf(\"\\n\\t %d\",a); // It\'ll print some garbage value;

So how does these garbage values are assigne

相关标签:
4条回答
  • 2020-11-29 12:39

    Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'? or something else?

    Correct. It is worth mentioning that the "allocation" of automatic variables such as int a is virtually nonexistent, since those variables are stored on the stack or in a CPU register. For variables stored on the stack, "allocation" is performed when the function is called, and boils down to an instruction that moves the stack pointer by a fixed offset calculated at compile time (the combined storage of all local variables used by the function, rounded to proper alignment).

    The initial value of variables assigned to CPU registers is the previous contents of the register. Because of this difference (register vs. memory) it sometimes happens that programs that worked correctly when compiled without optimization start breaking when compiled with optimization turned on. The uninitialized variables, previously pointing to the location that happened to be zero-initialized, now contain values from previous uses of the same register.

    0 讨论(0)
  • 2020-11-29 12:44

    int a;

    While declaring a variable, the memory is allocated. But this variable is not assigned which means the variable a is not initialized. If this variable a is only declared but no longer used in the program is called garbage value. For example:

    int a, b;
    
    b=10;
    printf("%d",b);
    return 0;
    

    Here it's only declared but no longer assigned or initialized. So this is called garbage value.

    0 讨论(0)
  • 2020-11-29 12:46

    Initially memory is having some values, those are unknown values, also called garbage values, when ever we declare a variable some memory was reserved for the variable according to datatype we specified while declaring, so the memory initial value is unknown value, if we initialize some other value then our value will be in that memory location.

    0 讨论(0)
  • 2020-11-29 13:03

    Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'?

    Exactly!

    Basically, C doesn't do anything you don't tell it to. That's both its strength and its weakness.

    0 讨论(0)
提交回复
热议问题