-5

I just made this short program. Can someone please explain why I am getting 2 as a result here?

Here is the code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int variable;
    int a;
    a=variable;
    a=200;
    printf("%d",variable);
    return 0;
}
waka
  • 3,362
  • 9
  • 35
  • 54
Kanishk Tanwar
  • 152
  • 1
  • 10

4 Answers4

5

Because you print the value of an uninitialized variable. It will have an indeterminate (and seemingly random) value.

The assignment you make to a just copies the value of variable and then of 200 into a. The value of variable remains unmodified and indeterminate.

I recommend you find a good beginners book or two to read.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Assigment operator (a = variable;) does not link the two variables, just assignes whatever value there is in the righthandside expression to the left handside.

You can visualize local variables as boxes where you can put values into.

tafa
  • 7,146
  • 3
  • 36
  • 40
2

At the beginning, you define two variables, a and variable. Note, that those variables at this point are not initialized. Right now, the compiler only knows that there are two variables of type int and their names, nothing more.

You then try to initialize variable a with the not initialized variable variable, the result should be clear: The two variables remain uninitialized.

Then you proceed and initialize a with 200, variable is still only defined, not initialized.

After that, you print the still uninitialized variable variable, which hasn't recieved any "real" value as of yet, only what already was "lying around" in memory when the compiler assigned that memory location to the variable. In your case, that was "2" (or at least, that's what printf could extract from there).

Further reading: C Variables. This explains how variables are defined, declared and initialized.

waka
  • 3,362
  • 9
  • 35
  • 54
  • Thanks man, I got it now – Kanishk Tanwar Oct 04 '17 at 10:50
  • @kanishktanwar: If your problem is solved, please consider accepting one of the answers you recieved by clicking the tick that appears next to them. That way you'll mark this question as "solved" (or "has an accepted answer" in StackOverflow terms). – waka Oct 04 '17 at 10:54
0

In c if you don't assign a value to the variable then it stores the garbage value which can be anything.In your code you did not assign the value to variable so it print 2 (which can be anything)