Twisted C++ code

Possible Duplicate: Undefined behavior and sequence points

 #include< iostream.h>
 int main()
 {
       int i=7,j=i;
       j=(i++,++i,j++*i);
       cout <<j;
       return 0;
 }

What will be the output of the C++ code?

It's my homework that my professor gave me.


It sometimes helps to convince people who don't believe this is undefined by actually compiling the program with several compilers and observing the results:

After fixing the iostream.h error,

  • g++ 4.5.2 prints 64
  • CLang++ 2.8 prints 63
  • Sun C++ 5.8 prints 63
  • MSVC 2010 prints 64
  • (oh, and, re-written to use CI/O, the original K&R C compiler on Unix 7 prints 63)


    [Edited to account for OP's question changing edit]:

    It's undefined as to what the output will be.


    There are the following errors in the code:

    #include <iostream.h> should be #include <iostream> ,

    j is uninitialized so the value of j++*i isn't known - OK, this got fixed in the edit,

    Besides, the assignment itself is improper. The convoluted line can be rewritten as:

    i++;
    ++i;
    j = j++ * i;
    

    And the last part is invalid for the reasons described here:

    Undefined behavior and sequence points

    链接地址: http://www.djcxy.com/p/73234.html

    上一篇: 意外的评估顺序(编译器错误?)

    下一篇: 扭曲的C ++代码