1

I have this piece of code here

#include<stdio.h>
void main()
{
    int i=0;
    printf("%d %d\n",++i,i++);
}

Which outputs

10z [achilles:~/Arena/c] $ ./a.out 
2 0

and the equivalent java program

12z [achilles:~/Arena/java] $ cat a.java 
class a
{
    public static void main(String[] args)
    {
        int i=0;
        System.out.printf("%d %d\n",++i,i++);
    }
}

which gives me

12z [achilles:~/Arena/java] $ java a
1 1

Why do they both print different results ??? Arent they both supposed to give me "1 1"

vikkyhacks
  • 3,190
  • 9
  • 32
  • 47
  • 1
    http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc for the C part. You're correct about the Java part though. – Mat May 12 '13 at 15:37
  • Actually NO it has nothing to do with that either, it has something to do with the fact that C does not guarantee the order in which it evaluates parameters passed to a function; so doing something like foo(x = 1+5, x = 2+3 ); will definitely be foo(6, 5); but at the end you won't know whether x = 6 or x = 5; – Ahmed Masud May 12 '13 at 15:38
  • @AhmedMasud : actually, yes, this has to do with undefined behaviour, as the code triggers undefined behaviour. – Daniel Kamil Kozar May 12 '13 at 16:17
  • I found the somewhat closer answer. C compiler every line by reading the program from **RIGHT TO LEFT** while I think java does it by reading the program from **LEFT TO RIGHT** (not sure about java but 100% sure about C. I wish I could answer to my own question but I am afraid tats not possible. I have made a brief comment here [link](http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c/16510753#16510753) – vikkyhacks May 12 '13 at 18:51
  • 1
    @vikkyhacks a) the order of evaluation of function arguments is unspecified. Arguments that are pushed on the stack are often evaluated right-to-left, but you can't rely on that [clang and gcc produce different output for the C, for example]. b) `printf("%d %d\n", ++i, i++);` modifies `i` twice without intervening sequence point, that invokes undefined behaviour [even `printf("%d %d\n", i, i++);` invokes UB and gives different output from clang and gcc]. – Daniel Fischer May 12 '13 at 20:06
  • **printf** with i++ and ++i have an **undefined behaviour**. see http://stackoverflow.com/questions/12529682/ – Pierre May 12 '13 at 15:37

0 Answers0