-1

I just tried giving the same values to a, b and d and every time I am running my code a random value is generated.

#include <stdio.h>

int main()
{
    int a = 4; //type declaration instructions
    int b = 999, c, d;
    a = b = d;

    printf("The value of a and b  is %d and %d \n", a, b);
    return 999;
}
the busybee
  • 10,755
  • 3
  • 13
  • 30
Satyam Shankar
  • 250
  • 2
  • 12
  • 4
    d has not been assigned a value – cup Jul 22 '21 at 05:26
  • 1
    Does this answer your question? [Is reading an uninitialized value always an undefined behaviour? Or are there exceptions to it?](https://stackoverflow.com/questions/67663015/is-reading-an-uninitialized-value-always-an-undefined-behaviour-or-are-there-ex) – phuclv Jul 22 '21 at 05:37
  • [Uninitialized variable in Cttps://stackoverflow.com/q/15268799/995714), [What will be the value of uninitialized variable?](https://stackoverflow.com/q/11233602/995714) – phuclv Jul 22 '21 at 05:39

3 Answers3

1

Lets go line by line.

  1. Declares an integer a, and initialises it to value 4

    int a = 4;
    
  2. Declares 3 integers b, c, d, and initialises b to 999. Since c and d are not initialised, they have garbage values(values previously stored in the block of memory which has now been allocated to c and d).

    int b = 999,c,d;
    
  3. Faulty Code. The garbage value in d is set to a and b

    a=b=d;
    

Correction - Either initialise d, or don't set a and b to d.

#include <stdio.h>

int main()
{
    int a = 4; //type decleration instructions
    int b = 999,c,d = 1000; // initialise d
    a=b=d;
    printf("The value of a and b  is %d and %d \n",a,b);
    return 999;
}
iBug
  • 35,554
  • 7
  • 89
  • 134
Anubhav Gupta
  • 421
  • 5
  • 12
1

The reason behind random value that you're getting on each execution of this program is that C assigns Garbage value(i.e. any random number) if the variable is not defined.

But this program is totally compiler dependent as few compilers assign the values by default to 0, if we don't define it.

So the output of this program may vary depending on the C compiler you are using. For example if you are using some online C compiler then most probably it will give 0 as output and some might give random value(Garbage value) as the output.

0
You declared variable c and d without assigning its values so random values are assigned to d .
hence assignment operator works right to left so 
    a=b=d
first:
   b=d works so random value of d goes in b 
and then : 
   a=b works so that random value goes in a
so try using=>
d=b=a
  you will get:
a=4
b=4
d=4
  • Welcome to StackOverflow! Please take the [tour] to learn how this site works. As you see, indenting your text formats it as source code. I'm sure this is not what you intended. Please [edit] your answer. – the busybee Jul 22 '21 at 05:55