Bug 26923

Summary: byte swap incorrect
Product: gcc Reporter: Younes <behloul.younes>
Component: cAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: normal CC: 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, jompo, krs, lid, lindahlb, lxg8906, mayer, mikaldaz, nakkore, nobs, pierre.van.de.laar_at_philips.com, qyang, ramiller, raoulgough, rglan, rjvbertin, robc, s9322036, SimonX200, smartmouse714, suan, super.aorta, svetozarmarkov, tczarnecki, vanveghel, vitaly, zshao
Priority: P3    
Version: 4.0.3   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:

Description Younes 2006-03-29 16:34:49 UTC
A peace of my code uses the two next macros (SWAP and InvSwap) to swap bytes, it worked for a long time under gcc-3.3 but not under gcc-4.0.3

under gcc-3.3:
InvWord(0xABCD) = 0xCDAB

under gcc-4-0.3:
InvWord(0xABCD) = 0xCD00   !!!!


############ FILE STARTS HERE  ##################
#define SWAP(x,y)  (x)^=(y)^=(x)^=(y)
#define InvWord(x) SWAP(*((char *)(&(x))),*((char *)(&(x))+1))
int main()
{
unsigned short data_length;
data_length = 0xABCD;
InvWord(data_length);
return 0;
}


############ FILE ENDS HERE  ###################
I've also tried to use __bswap_16 but id did nothing :(

thanks in advance
Comment 1 Pawel Sikora 2006-03-29 18:51:02 UTC
It's not a gcc bug. The code relies on the results of intermediate
subexpressions.  According to Stroustrup, The C++ Programming Language, section
6.2.2, "The order of evaluation of subexpressions within
an expression is undefined."

You should use sequence points e.g.:

        a ^= b, b ^= a, a ^= b;

This is a dup of PR11751
Comment 2 Andrew Pinski 2006-03-29 19:26:07 UTC

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