Bug 32067

Summary: template<class T> XOR-Swap(T &a, T &b); error with -O0 option
Product: gcc Reporter: Nan Wang <nanericwang>
Component: c++Assignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: critical CC: alexey, algorithmus, asokumar, av1474, bala, barnarr, behloul.younes, bmead15, buergel, carpman, chuchunxin, devnull, d_picco, eric.mcvicker, fuchsia.groan, gaurav_har, gcc-bugs, gcc, ggs, jandres, janis, jesser, jompo, krs, lid, lindahlb, lxg8906, mayer, mikaldaz, mike.clarkson, nakkore, nanericwang, nobs, pierre.van.de.laar_at_philips.com, qyang, ramiller, raoulgough, raphael.ribas, rglan, rjvbertin, robc, s9322036, SimonX200, smartmouse714, suan, super.aorta, svetozarmarkov, tczarnecki, vanveghel, vitaly, windows2000d, zshao
Priority: P3    
Version: 4.1.2   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:

Description Nan Wang 2007-05-24 12:16:01 UTC
It gives an unexpected result while doing xor operation on a templated class.

For sample, here is my simple code:
------------------------------------------------------
#include <iostream>

using namespace std;

template
<class T>
inline void XOR-Swap(T &a, T &b)
{
        if (a != b)
        a ^= b ^= a ^= b;
};

int main()
{
        int a = 10;
        int b = -3;
        XOR-Swap(a, b);

        cout << a << endl;
        cout << b << endl;

        return 0;
}
-----------------------------------------------------
Results:

1. with "-O0": Incorrect
-------------------
0
10
-------------------


2. with "-O1": Correct
-------------------
-3
10
-------------------


Any comment?
Comment 1 Pawel Sikora 2007-05-24 12:31:39 UTC
(In reply to comment #0)

> Any comment?

this is an example of undefined behaviour.
http://blogs.msdn.com/rick_schaut/archive/2004/03/06/85357.aspx
Comment 2 Andrew Pinski 2007-05-24 16:21:25 UTC
http://gcc.gnu.org/bugs.html#nonbugs_c

*** This bug has been marked as a duplicate of 11751 ***