What happens when a variable is not initialized in main function?

When a variable is not initialized in main function it contains garbage value. This can be well seen from the example below



main()

{

int x;

printf( “%d”,x);

z= sample()

}


sample()

{

printf(“Testing program”);

}



Output is



x=80

Testing program



The above program prints a garbage value and the output testing program .This is because the variable x is not initialized and so the variable x had garbage value which is printed first then the function sample is called which gave output as testing program.  Thus it is essential to initialize variables in main () function.

Questions by GeekAdmin   answers by GeekAdmin

Showing Answers 1 - 1 of 1 Answers

kvsmp2

  • Oct 13th, 2006
 

As the above illustrates that if we are not intializint the varaible we get garbarge value.

This is because when you define a variable the compiler calls the os then os allocates the required memory (which is free or ram) then returns the address to the complier. if we are not initializing the variable then it gives the garbage value whatever that address contains 

  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