-1
int main()
{
    int value = 4321;
    int *ptrVal = &value;
    printf("%d %d",++value,(*(int*)ptrVal)--);
    return 0;
}

How does pre-increment/post increment works in above print statement ?

And why is answer 4321 4321 ?

simonc
  • 41,632
  • 12
  • 85
  • 103
Rohit
  • 6,941
  • 17
  • 58
  • 102

2 Answers2

3

You are modifying the object value twice between two sequence points: you are invoking undefined behavior. Undefined behavior means your program can print 4321 4321, print 42 or even just crash.

A correct version of your program would be:

int value = 4321;
int *ptrVal = &value;

++value;
(*ptrVal)--;  // no need to cast to int *

printf("%d %d", value, *ptrVal);  // same as printf("%d %d", value, value);

Of course you don't need any temporary pointer to achieve this.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 1
    Since the questioner's program was clearly specifically contrived for this slightly-different version of "what happens when I `printf("%d %d\n",++i, i--)`", I disagree with your assertion that your example is a correction version of the program: It is merely a version of the program that does not invoke Undefined Behavior. Regardless of the specific implementation, the primary purpose of the questioner's program is to demonstrate Undefined Behavior for the purpose of inquiry. There can be no "correct" version of Undefined Behavior. – This isn't my real name Jun 10 '13 at 23:06
  • @ElchononEdelson *I disagree with your assertion that your example is a correction version of the program: It is merely a version of the program that does not invoke Undefined Behavior.* That was exactly the sense of my assertion. A correct version of the program: a version of the program that does not invoke undefined behavior. A program invoking undefined behavior being an *erroneous* program. – ouah Jun 11 '13 at 08:39
  • I don't agree. I don't see how you can call a program "correct" if it doesn't meet the design goal. In this case, The design goal appears to be "violate the rules of the language for discussion purposes", so I continue to assert that there can be no correct version of this program. Additionally, using the alternate interpretation of "what it looks like the programmer was intending if this were found in live code", the use of the post-decrement operator suggests that when correcting the code, we should decrement `(*prtVal)` _after_ the call to `printf()`. – This isn't my real name Jun 11 '13 at 20:04
1

The code above is just broken. It is unspecified how it will work or what the answer will be. You need a sequence point between modifications or modifications and accesses.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278