Why after defining variable and while accessing ,its not showing garbage value in C?

81 views Asked by At

When after only defining any number of variables in a source code and trying to print it without initializing it.I am getting the values zero for the last two variables and one or two some other variables.The Last two variables is like blindly(at least to me) we can say like it is declared to zero.

As I am defining the variable inside the function the storage class is defaultly auto and its value is garbage value in this case why is it showing zero for the last two variables every time and for some other variables which is zero is not changing after multiple execution.

NOTE

1.If I take the last two zero values and other variables with zeroes as as garbage then why is the zeroes not changing after executions whereas other values are changing after executions.

2.Anyways the last two variable with any number of variables defined is gonna be zero.Why this is only happening with the last two variables.

3.This is not only happening with online compiler I have tried with vs code using gcc compiler in Windows 8 and Linux(pop Os) as the C program is platform dependent.

Same is in Case with CPP

First Execution Pic

Second Execution Pic

Code

#include<stdio.h>
int main(){
   int a,b,c,d,e,f;
   printf("%d\t%d\t%d\t%d\t%d\t%d\t",a,b,c,d,e,f);
   return 0;
}

Is there any logic behind the execution.Somebody please explain.Thank you.

1

There are 1 answers

6
user12002570 On

If you don't initialize a variable and use its value, it will result in undefined behavior. For example,

int i; //i has not been initialized and so holds garbage value
printf("%d\n",i);//this will lead to undefined behavior. 

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.