What is the difference between volatile and local variable in c?

c

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

Code 1:

   main()
  {
   int a=5;
   printf("Value : %d %d %d %d\n",a++,a++,++a,a++);
  }
  ANS:
  Value : 8 7 9 5

Code 2:

   main()
  {
   volatile int a=5;
   printf("Value : %d %d %d %d\n",a++,a++,++a,a++);
  }
  ANS:
  Value : 8 7 7 5

Code 3:

   main()
  {
   int a;
   scanf("%d",&a);
   printf("Value : %d %d %d %d\n",a++,a++,++a,a++);
  }
  INPUT is 5
  ANS:
  Value : 8 7 7 5

How the above programs are getting different outputs ?

I experimented volatile variable , it is used to prevent compiler optimizations.
So I understood the Code 2. But I want to know that ,how the Code 1 and 3 are working ?

Best Answer

volatile is to tell the compiler to read the value from memory every time as opposed to do any caching of values as part of its optimizations.

Your code exhibits undefined behaviour which is not going to be changed in anyway by using volatile.