Rule of thumb for foo++

Ed Keizer keie at vu44.UUCP
Tue Jan 10 02:12:00 AEST 1984


Mark Plotnick (mit-eddie!mp) mentioned
        ( (foo+=1) - 1 )
as a rule of the thumb for post-increment
operators like in
        foo++
and said that he didn't know any off-hand exceptions.
Well, I met one last year that shows one of the pitfalls of
overflow.
Assume that foo is declared as an unsigned short and that the
C compiler uses 32-bit int's. Now see what happens if we give
foo the value 0xFFFF.

foo++ delivers the value 0xFFFF, but
( (foo+=1) -1 ) delivers the value 0xFFFFFFFF,
because the result of (foo+=1) is 0 and not 0x10000.
The C reference manual is quite explicit here:
"The value ___of the assignment expression___ is the value
stored in the left operand after the assignment has taken place."

                                        Ed Keizer
                                        Vrije Universiteit
                                        Amsterdam
                                        ...!mcvax!vu44!keie



More information about the Comp.lang.c mailing list