the output is 1.why???

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • indiver
    New Member
    • Aug 2010
    • 2

    the output is 1.why???

    main() { int i=5; printf(“%d” ,i=++i ==6); }
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    Because i=++i promotes undefined behavior and the output could be any value.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      I don't believe there is any undefined behavior here. Your snippet is equivalent to
      Code:
      main()
        {
        int i = 5;
        i = (++i == 6);
        printf(“%d”, i);
        }
      The output of the == operator is either 1 or 0. In this case, it is 1 because ++i is equal to 6.

      I assume the odd format string is a cut-and-paste artifact. By the way, the proper return value of main is int.

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        Folks,

        All constructs of the form
        Code:
        i = i++;
        are in the realm of undefined behaviour according to the language specification.

        Basically all expressions have undefined evaluation order, so an expression that has two side effects on a variable is ambiguous.

        Comment

        Working...