c# XOR equals ( ^= ) bug?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jason

    #1

    c# XOR equals ( ^= ) bug?

    Could someone please tell me if this is a bug or is it by
    design?

    I am using the triple XOR swap trick for two integers. I
    show three "techniques ", but only the first one works.
    All three work in C++, but I get weird results in c#.

    technique 1: (works in C#)
    x ^= y;
    y ^= x;
    x ^= y;

    technique 2 (doesn't work correctly in C#, does in C++)
    x ^= y ^= x ^= y;

    technique 3 doesn't work correctly in C#, does in C++)
    x ^= (y ^= (x ^= y));


    Here is some code you can cut and paste into vs.net.
    Uncomment the parts in the Swap() function to try each
    technique and see that only the first one works.


    class Class1
    {
    [STAThread]
    static void Main(string[] args)
    {
    int x = 1;
    int y = 2;
    Console.WriteLi ne("before swap");
    Console.WriteLi ne("x: {0}", x);
    Console.WriteLi ne("y: {0}", y);

    Swap(ref x, ref y);

    Console.WriteLi ne("\nafter swap");
    Console.WriteLi ne("x: {0}", x);
    Console.WriteLi ne("y: {0}", y);
    }

    public static void Swap(ref int x, ref int y) {

    //Technique 1
    // this works perfectly, just as in c++
    x ^= y;
    y ^= x;
    x ^= y;

    //Technique 2
    // Put all on a single line.
    // However, this produces incorrect results in
    // C#, but works correctly in C++
    //
    //x ^= y ^= x ^= y;

    //Technique 3
    // This also doesn't work. C# should evaluate
    // from the right (like C++), but something
    // isn't working.
    //
    //x ^= (y ^= (x ^= y));
    }
    }
  • Jason

    #2
    c# XOR equals ( ^= ) bug?

    two things more:

    1. I am using VS.Net 2003

    2. There seems to be a bug in the debugger.
    Highlighting an expression like "x ^= y" with the mouse
    and then hovering over the operator will display a
    tooltip with the answer. However the original values
    change and from that point on the values may not be
    correct!

    To reproduce in the code from my previous post:

    1. Load the code from my previous post. Uncomment the
    first technique. comment the others out.

    2. Put a breakpoint on the first of the three lines of
    the triple XOR swap.

    public static Swap( ref int x, ref int y)
    {
    breakPoint--> x ^= y;
    y ^= x;
    x ^= y;
    }

    3. run the code in debug mode. the program will stop on
    the breakpoint.

    4. now, without advancing (no F10), highlight the one of
    the expressions with the mouse and then hover over the
    operator (^=) in that line. The tooltip will show the
    results of the evaluation, but now the values in x and y
    are changed permanently.

    NOTE: when highlighting, make sure not to highlight the
    semicolon at the end of the line or the tooltip won't
    show.

    Jason P.

    Comment

    • Jason

      #3
      Re: c# XOR equals ( ^= ) bug?

      Michael,
      Thanks for answering back so soon.
      [color=blue]
      >In C# it looks like what is happening is that x is being[/color]
      xored with its[color=blue]
      >original value in the last step, because the result I[/color]
      get is 0.

      I too get the 0 (zero) for the result, but as you know
      it's wrong.
      [color=blue]
      >And what we have here is basically the old difference[/color]
      between[color=blue]
      >call-by-reference and call-by-value. In C++, variables[/color]
      are memory[color=blue]
      >locations. In C#, they are values. So in C#, the[/color]
      compiler first grabs the[color=blue]
      >current values of x and y, filling them in for the[/color]
      appropriate rvalue[color=blue]
      >variables, and then does the execution.[/color]

      Yes you seem to be on to something, however all three
      techniques are functionally equivilant. So they sould all
      work. C# is supposed to evaluate from the right in this
      situation (just as C++ would).


      Also, take a look at my other post about a bug in the
      debugger. See what you think.
      Jason P.


      Comment

      • Jason

        #4
        Re: c# XOR equals ( ^= ) bug?

        Thanks Mr. Culley.

        The thread made sense, especially this post:

        -------------------------------
        I believe there is a difference how C++ and C# consider
        compound assignment
        operators. In C++ left operand is evaluated as lvalue and
        stored, after that
        right operand is evaluated as rvalue and then compound
        assignment operator
        is applied to lvalue and rvalue.

        On the other hand C# expands compound assignment operator
        (A^=B => A=A^B)
        and evaluates left operand (A) first time as lvalue, than
        right operand
        (A^B) as rvalue and then performs assignment. In C#
        A^=B^=A^=B is equal to
        A=A^(B=B^(A=A^B )) where arguments are evaluated from left
        to right.
        --
        Vladimir Nesterovsky
        ---------------------------------

        Comment

        • Adam Benson

          #5
          Re: c# XOR equals ( ^= ) bug?

          Hi,

          This is only a general observation, for what its worth.
          But if 1 line of code is this difficult to figure out, then surely it's not
          worth it : turn it into several statements that are obvious.

          Yes, it's less efficient (or maybe not after the optimizer has done its job)
          but the time saved in coding the thing up, and the time saved if anyone else
          has to pick up your code is worth it.

          Only a suggestion.

          Regards,

          Adam.

          --
          Adam Benson
          adam.benson@NOS PAM.omnibus.co. uk
          =============== =============== ====


          Comment

          • Michael A. Covington

            #6
            Re: c# XOR equals ( ^= ) bug?

            In general, it appears that in C#, if you evaluate


            x + blah


            where + is any operator, and blah contains something that changes the value
            of x,

            then C# will use the *old* value of x for the first argument of +, and C++
            will use the *new* value.


            I still don't know if this is intentional, or wise. As an old Pascal
            programmer, I tend to that that assignments ought not to be mixed up with
            evaluations anyhow. And I note that C# is the work of another old Pascal
            programmer (Anders Hejlsberg, of Turbo Pascal fame).






            Comment

            • Michael A. Covington

              #7
              Re: c# XOR equals ( ^= ) bug?

              > This is only a general observation, for what its worth.[color=blue]
              > But if 1 line of code is this difficult to figure out, then surely it's[/color]
              not[color=blue]
              > worth it : turn it into several statements that are obvious.[/color]

              I agree wholeheartedly, but at the same time, we've unearthed a fairly deep
              peculiarity of C# semantics. It's bothersome, because things that look like
              C ought to act like C.



              Comment

              • Michael A. Covington

                #8
                Re: c# XOR equals ( ^= ) bug?


                "Iain Simpson" <isimpson@kelvi nconnect.com> wrote in message
                news:%232QLnVkY DHA.2424@TK2MSF TNGP12.phx.gbl. ..[color=blue][color=green]
                > > technique 1: (works in C#)
                > > x ^= y;
                > > y ^= x;
                > > x ^= y;
                > >
                > > technique 2 (doesn't work correctly in C#, does in C++)
                > > x ^= y ^= x ^= y;
                > >
                > > technique 3 doesn't work correctly in C#, does in C++)
                > > x ^= (y ^= (x ^= y));[/color]
                >
                >
                > This all depends on what you interpret to be "correct" behaviour.
                >
                > In general I would recommend against using more than one ?= type operator[/color]
                on[color=blue]
                > the same line.
                >
                > The C# specification may well say that these expressions are evaluated[/color]
                right[color=blue]
                > to left, but someone who doesn't know this, and is reading your code might[/color]
                get[color=blue]
                > confused as to the final result of your expression.
                > Regardless of the specification, the semantics of this are unclear, and[/color]
                almost[color=blue]
                > certainly inconsistent when you move between different (C/C++) compilers.[/color]

                Can we find C++ compilers that go different ways on this? That would be
                very interesting.
                [color=blue]
                > I don't think that technique 2 would be more efficient than technique 1,[/color]
                as[color=blue]
                > the compiler is probably going to split your line up into 3 separate
                > operations anyway.[/color]

                Yes, there's no difference in the amount of work done by the computer.

                Actually, I don't like tricks, so I'd see if C# has a built-in "swap"
                function (it may well), and if not, do:

                t = x;
                x = y;
                y = t;

                But this was interesting anyhow!


                Comment

                • Jon Skeet

                  #9
                  Re: c# XOR equals ( ^= ) bug?

                  Michael A. Covington <Michael@Coving tonInnovations. com> wrote:[color=blue]
                  > In general, it appears that in C#, if you evaluate
                  >
                  > x + blah
                  >
                  > where + is any operator, and blah contains something that changes the value
                  > of x,
                  >
                  > then C# will use the *old* value of x for the first argument of +, and C++
                  > will use the *new* value.[/color]

                  Yes. As per the spec:

                  <quote>
                  The order in which operands in an expression are evaluated, is left to
                  right.
                  </quote>
                  [color=blue]
                  > I still don't know if this is intentional, or wise.[/color]

                  I think it's simple and reasonably natural, even if it's not the way
                  that C does it (assuming it's even well defined in C - I haven't
                  checked).

                  In another post you wrote:
                  [color=blue]
                  > I agree wholeheartedly, but at the same time, we've unearthed a fairly
                  > deep peculiarity of C# semantics. It's bothersome, because things that
                  > look like C ought to act like C.[/color]

                  I would say it's more that we've unearthed a case where C# has
                  corrected a fairly deep peculiary of C semantics. There's no reason why
                  it *should* evaluate the second operand first, and from a human
                  "reading left to right" perspective, it makes more sense to evaluate
                  the first operand first.

                  There are various ways in which C# doesn't act like C despite looking
                  like it (conditionals having to be boolean, for instance) and I for one
                  am grateful for that :)

                  --
                  Jon Skeet - <skeet@pobox.co m>
                  Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                  If replying to the group, please do not mail me too

                  Comment

                  • Hong Hao

                    #10
                    Re: c# XOR equals ( ^= ) bug?

                    Another way to look at the issue has to do with the order in which
                    parameters passed into a function call are evaluated. If

                    int xor(int, int)

                    is a functin call that takes two integers, preform a xor operation on them
                    and return the result, the expression

                    x ^= y ^= x ^= y;

                    is then equivalent to, for variable x,

                    x = xor(x, xor(y, xor(x, y)));

                    It seems the C# evaluates the parameters from left to right, while C++ does
                    the reverse.

                    These behaviors are best demostrated with the following examples. First is a
                    simple C++ code:


                    #include <iostream.h>

                    int func1()
                    {
                    cout << "func1 called." << endl;
                    return 1;
                    }

                    int func2()
                    {
                    cout << "func2 called." << endl;
                    return 2;
                    }

                    void func3(int i1, int i2)
                    {
                    cout << "func3 called with " << i1 << " and " << i2 << endl;
                    }

                    void main(void)
                    {
                    func3(func1(), func2());
                    }

                    This code produces the following output

                    func2 called.
                    func1 called.
                    func3 called with 1 and 2

                    The equivalent C# console application is

                    using System;

                    namespace ConsoleApplicat ion1
                    {
                    class Class1
                    {
                    [STAThread]
                    static void Main(string[] args)
                    {
                    func3(func1(), func2());
                    }

                    static int func1()
                    {
                    Console.WriteLi ne("func1 called.");
                    return 1;
                    }

                    static int func2()
                    {
                    Console.WriteLi ne("func2 called.");
                    return 2;
                    }

                    static void func3(int i1, int i2)
                    {
                    Console.Write(" func3 called with ");
                    Console.Write(i 1);
                    Console.Write(" and ");
                    Console.WriteLi ne(i2);
                    }
                    }
                    }

                    which produces the following output

                    func1 called.
                    func2 called.
                    func3 called with 1 and 2

                    The outputs clearly showed the difference in ordering.

                    Hong Hao

                    "Michael Culley" <mculley@NOSPAM optushome.com.a u> wrote in message
                    news:O9PDo4hYDH A.440@tk2msftng p13.phx.gbl...[color=blue]
                    > We've had this exact same question before, see below. See
                    >
                    >[/color]
                    http://groups.google.com/groups?q=%2...lm=6591445.030[color=blue]
                    > 1161319.2408f90 1%40posting.goo gle.com&rnum=1
                    >
                    > First post of the thread is below.
                    >
                    > --
                    > Michael Culley
                    >
                    >
                    >
                    >
                    > There's an old trick in C to swap 2 variables. You just xor the two
                    > variables like this:
                    >
                    > A^=B^=A^=B;
                    >
                    > I don't really care to swap two integers like that, but when I tried
                    > it something unexpected happened. With:
                    >
                    > int A=5, B=9;
                    > A^=B^=A^=B;
                    >
                    > I got A==0 and B==5. But with
                    >
                    > int A=5, B=9;
                    > A^=B; B^=A; A^=B;
                    >
                    > I got A==9 and B==5. Java produces the same result. Both languages
                    > seem to use the original value of A for the final xor rather than the
                    > one assigned in the first xor.
                    >
                    > My question is, what's the general rule being applied here?
                    >
                    >[/color]



                    Comment

                    • Harry Bosch

                      #11
                      Re: c# XOR equals ( ^= ) bug?

                      Jon Skeet <skeet@pobox.co m> wrote:
                      [color=blue]
                      > There are various ways in which C# doesn't act like C despite looking
                      > like it (conditionals having to be boolean, for instance) and I for
                      > one am grateful for that :)[/color]

                      Absolutely!

                      --
                      harry

                      Comment

                      • Michael A. Covington

                        #12
                        Re: c# XOR equals ( ^= ) bug?


                        "Jon Skeet" <skeet@pobox.co m> wrote in message
                        news:MPG.19a5a0 717c073e6698a30 a@news.microsof t.com...
                        [color=blue][color=green]
                        > > I agree wholeheartedly, but at the same time, we've unearthed a fairly
                        > > deep peculiarity of C# semantics. It's bothersome, because things that
                        > > look like C ought to act like C.[/color]
                        >
                        > I would say it's more that we've unearthed a case where C# has
                        > corrected a fairly deep peculiary of C semantics. There's no reason why
                        > it *should* evaluate the second operand first, and from a human
                        > "reading left to right" perspective, it makes more sense to evaluate
                        > the first operand first.
                        >
                        > There are various ways in which C# doesn't act like C despite looking
                        > like it (conditionals having to be boolean, for instance) and I for one
                        > am grateful for that :)[/color]

                        Actually you make very good points.

                        In C, it has become customary to use various constructs in peculiar and
                        confusing ways.

                        Someone else indicated that this particular point of semantics is actually
                        undefined in C and C++, and it's just happenstance that most compilers go
                        the opposite way than C#. I wonder if that is correct.


                        Comment

                        • Harry Bosch

                          #13
                          Re: c# XOR equals ( ^= ) bug?

                          "Michael A. Covington" <Michael@Coving tonInnovations. com> wrote:
                          [color=blue]
                          > At one time my name for C was "UPL" ("uninitiali zed pointer language")
                          > and a lot of those GPF's in Windows, which the public was blaming on
                          > Windows, were of course due to klutzy application programming.
                          > Programmers have gotten a little better. But I never liked the
                          > penchant for obscurity that seemed to be a characteristic, not of the
                          > C language, but of the C community.[/color]

                          UPL -- That's funny! :-) I call it "C Programmer's Disease" when a person
                          actually *likes* coding that way :-) Another symptom of this disease is an
                          obsession with optimizing everything, even things which may be executed
                          rarely, or only once in the entire app. It's basically an inability to
                          evaluate the difference between critical and non-critical code. They don't
                          need profilers, because they spend all their time optimizing EVERYTHING :-)

                          --
                          harry

                          Comment

                          • Jason

                            #14
                            Re: c# XOR equals ( ^= ) bug?

                            Of course, I'm not a noob. I just wanted to see what
                            others thought.

                            I also don't like to use "trick" programming (all on one
                            line stuff), but I just wanted to investigate this
                            difference between C++ and C#.

                            Comment

                            • Michael A. Covington

                              #15
                              Re: c# XOR equals ( ^= ) bug?


                              "Jason" <jpursell@u.was hington.edu> wrote in message
                              news:0de201c362 b2$85d9f3a0$a00 1280a@phx.gbl.. .[color=blue]
                              > Of course, I'm not a noob. I just wanted to see what
                              > others thought.
                              >
                              > I also don't like to use "trick" programming (all on one
                              > line stuff), but I just wanted to investigate this
                              > difference between C++ and C#.[/color]

                              Understood. It was an interesting adventure!


                              Comment

                              Working...