A simple non-portable expression tha

Tim Smith tim at ism780c.UUCP
Wed Apr 16 07:21:30 AEST 1986


In article <32700003 at siemens.UUCP> jrv at siemens.UUCP writes:
>>If R and L are longs, and i is an int, then the expression
>>
>>	L = R + 2 + i;
>>
>>is non-portable.  Lint, however, does not complain about this.
>
>I must be missing something. Why is this non-portable?
>

Since + is associative and commutative, the compiler is free to
re-order the expression.  If you are on a machine where and int
is shorter than a long, and if the compiler decided to do the
2+i first, you may get an overflow, whereas if the compiler
does the R+2 first there is no problem.

To make this expression portable, it needs to be

	L = R + 2 + (int)i;
or
	L = R + 2L + i;

-- 
Tim Smith       sdcrdcf!ism780c!tim || ima!ism780!tim || ihnp4!cithep!tim



More information about the Comp.lang.c mailing list