-4
int main(void)
{

  int i; 
  scanf( "%d", &i );   
  i = i++ * i++ ;
  printf( "%d", i );
  getchar();
  getchar();
  return 0; 

}

Why does this program print 25 instead of 27 if I input 5 ?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Shinz6
  • 147
  • 1
  • 2
  • 10
  • 2
    Beacause of [Undefined Behavior](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAA&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FUndefined_behavior&ei=KN0XVcS-Cc-XuATElYDIDg&usg=AFQjCNHohj__31X4qzn8FC2iW1_0ecu4_w&sig2=d7asJwhqL2FdL8eWAMreEg) – Spikatrix Mar 29 '15 at 11:04
  • 1
    Why would you expect 27? – SMA Mar 29 '15 at 11:05
  • 2
    @SMA: because of Undefined Behavior! Since the behavior is undefined, one can expect it to return any number. '27' sounds as reasonable as '42'. – Jongware Mar 29 '15 at 11:19
  • There ought to be a way of filtering this garbage out:( – Martin James Mar 29 '15 at 11:39

1 Answers1

5
i = i++ * i++ ;

is undefined behaviour and so can do whatever it pleases, such as return 25, return 27, return 30 (which probably makes more sense than 27), format your hard disk, or even laugh derisively at you.

:-)

The C standard (both C99 and C11, and possibly earlier though I haven't checked) has things known as sequence points, and you are not permitted to change the same variable twice without an intervening sequence point (of which the multiplication symbol * was not one).

You can see what are considered sequence points in Appendix C of both those iterations of the standard.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953