1

Just wondering how exactly volatile keyword works internally.

Tried with GCC and Turbo C(DOS based) both cases it behaves in different manners.

volatile int iData;
iData = 5;
printf("%d %d %d %d %d %d\n", ++iData, iData++, iData++, ++iData, iData, iData++);

does the output depend upon printf function data passing or compiler based?

Thank you Cheers !!

  • 6
    The output can depend on anything you want because your program invokes undefined behavior. And it does so irrespective of `iData` being or not being `volatile`. This is a duplicate question. – Alexey Frunze Apr 10 '13 at 05:11
  • look up `ISO/IEC TR3` standard draft section `6.7.3.6`. [Link](www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf).the section is not difficult to understand – Koushik Shetty Apr 10 '13 at 05:23
  • Don't try with Turbo C, it doesn't follow any version of the C standard. Furthermore your example is nonsense and relies on both undefined and unspecified behavior. – Lundin Apr 10 '13 at 06:49

1 Answers1

2

You are invoking undefined behaviour by modifying iData more than once in the same statement. Since the behaviour is undefined, different compilers can do different things for it and neither of them is wrong. So you really don't want undefined behaviour in your code.

See Why are these constructs (using ++) undefined behavior? for more details.

Note: the odd behaviour in your code has nothing to do with the volatile keyword. For more information on volatile see Why is volatile needed in C?

Community
  • 1
  • 1
Scott Olson
  • 3,513
  • 24
  • 26
  • Thank you Scott. I would like to know how exactly volatile works ? –  Apr 10 '13 at 05:13
  • 1
    @Planet: Then post a new question. The code in your question has nothing to do with how `volatile` works because the whole program has undefined behavior due to modifying an object multiple times without an intervening sequence point. – R.. GitHub STOP HELPING ICE Apr 10 '13 at 05:22
  • @Planet I added a link at the bottom that should explain `volatile`. – Scott Olson Apr 10 '13 at 05:29