Question

This code :

#include <stdio.h>

static void swap(unsigned char& a, unsigned char& b)
{
    unsigned char t = a;
    a = b;
    b = t;
}

int main()
{
    const unsigned bgr = 0x0000FF;
    swap(((unsigned char*) &bgr)[0], ((unsigned char*) &bgr)[2]);
    printf("0x%06X\n", bgr);
}

output:

0x0000FF

Where are changes made by swap ?

Was it helpful?

Solution

You are trying to modify bgr. bgr is const. Modifying a const variable is undefined behaviour. This can manifest itself in many ways, and you cannot rely on any specific behaviour. A good way to figure out what is happening on your platform is to look at the generated assembly code.

OTHER TIPS

bgr is const in this case. My guess is that you're invoking undefined behavior by attempting to swap it's first and last byte. Removing the const results in an actual swap on my platform:

#include <stdio.h>

static void swap(unsigned char& a, unsigned char& b)
{
    unsigned char t = a;
    a = b;
    b = t;
}

int main()
{
    unsigned bgr = 0x0000FF;
    swap(((unsigned char*) &bgr)[0], ((unsigned char*) &bgr)[2]);
    printf("0x%06X\n", bgr);
}

Now compile and run:

$ g++ -Wall foo.cpp ; ./a.out 
0xFF0000

Because you declared bgr to be const, you've fallen victim to a compiler optimization. Rather than passing the actual variable to printf, it passed a constant value.

If the variable had not been declared const the optimization wouldn't have been made.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top