Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postincrement in Left side

Tags:

c

pointers

I was under the impression that postincrement(OR preincrement) can be done only on right Hand side of equal(=). But I am able to compile below piece of code. Can you help me in understanding this specific code especially below line. source : http://www.ibm.com/developerworks/library/pa-dalign/

*data8++ = -*data8;


void Munge8( void *data, uint32_t size ) {
    uint8_t *data8 = (uint8_t*) data;
    uint8_t *data8End = data8 + size;

    while( data8 != data8End ) {
        *data8++ = -*data8;
    }
}
like image 876
kumar Avatar asked Jun 18 '12 18:06

kumar


2 Answers

So, I'm fairly sure that this is undefined behavior. There is no sequence point other than the final semicolon in:

    *data8++ = -*data8;

If data8 is equal to 0x20, is this equal to:

    *(0x20) = -*(0x20);

or

    *(0x20) = -*(0x24);

Because there is no way to make this decision, (because you've edited a variable while reading it twice, with no interleaving sequence point), this is undefined behavior.


We can talk about what the following piece of code does though. Which is likely what is intended by the above code.

while( data8 != data8End ) {
    *data8 = -*data8;
    data8++;
}

What you're doing here is hopefully more straightforward. You're taking your input array, and looking at it so it's a series of 8 bit numbers. Then, in-place, you negate each one.

like image 119
Bill Lynch Avatar answered Oct 05 '22 14:10

Bill Lynch


Your impression is wrong, I guess. You can definitely do things like:

*a++ = *b++;

In fact, that's often how strcpy is implemented. You can even have the post- or pre-increments without an = at all:

a++;
like image 21
Carl Norum Avatar answered Oct 05 '22 14:10

Carl Norum