Garbage Value

In C if a variable is not assigned a value then why does it take garbage value?

Questions by ajayvyas

Showing Answers 1 - 21 of 21 Answers

mihir_void

  • Mar 5th, 2009
 

This happens only in case of local varibales. As memory for local variables are allocated on stack and while allocating the memory the runtime system does not clear the memory before allocating it to the variable unlike in case of allocating memory in heap for global and static variables. Hence the default value of local varibles beomes the content of its memory on stack while that of constant and static variables is 0.

kbjarnason

  • Jul 1st, 2010
 

In C, if a variable is not assigned a value, then evaluating the variable is an undefined operation.  It _may_ simply result in a garbage value, or it may crash your computer, or it may do any other thing you can imagine.

As an example, suppose an implementation only actually assigned the memory for the variable at the time of assignment.  That is, "int x;" reserves no actual memory for x, but a subsequent "x = value;" causes the memory to be set aside for x.

Now consider the following:

int x, y;

y = x;

The implementation sets aside memory for y, because y is being assigned to.  However, x was never assigned to, so there is no memory associated with x; the assignment is attempting to read a value from a memory location which doesn't exist.

In such an implementation, one would likely expect a crash, rather than a garbage value, but ultimately, with undefined behaviour, expecting _any_ particular result is futile - the behaviour is undefined, the implementation is allowed to do anything it pleases.

  Was this answer useful?  Yes

Karudaiyar

  • Nov 6th, 2014
 

Garbage means waste so in C Language the variable is not assigned it takes a garbage value. For an ex.

Code
  1. #include<stdio.h>

  2. void main() {

  3. int a;

  4. printf("%d",a);

  5. }


For the above pgm i didnt mention any value.so it takes a garbage....no value has assigned....

  Was this answer useful?  Yes

Abhi

  • Jun 9th, 2017
 

Can two different variable have same garbage value ?

  Was this answer useful?  Yes

Nilaya

  • May 2nd, 2018
 

As the program execution in C is handled by stacks in the computer, when a variable is not assigned a value, the stack assigns a garbage value for it.

  Was this answer useful?  Yes

aprajita

  • Mar 28th, 2019
 

this is giving 0 all the time

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions