R
Rennie deGraaf
In the last few days, I have discovered two "interesting" behaviours of
the C language, both of which are apparently correct. Could someone
please explain the reasoning behind them?
1. The operators '^', '&', and '|' have lower precedance than '==',
'!=', '>=", etc. I discovered this when the statement "if (array1 ^
array2 == 0xff)" failed to do what I expected. To me, it doesn't
make any sense to give the bitwise operators lower precedance than
comparators. I can't see any situation where someone would want to
perform a bitwise operation on a truth value, but that is what the
language specifies for the above expression.
2. In C99, the expression 'a%b' where a<0 and b>0 will return a negative
result (K&R lets this be machine dependent). While it is technically
correct (-1 is congruent to 6 mod 7), it isn't exactly what most people
expect. Mathematically, the congruence classes modulo n are usually
expressed as [0], [1], ... [n-1]. The value -1 would be a member of the
congruence class [n-1]. So, when I'm performing certain operations, I
have to check if a number is negative, and if so, add the modulus to the
residue to get a sensible result. (For example, when subtracting two
struct timevals, and passing the result to select(). select() will barf
if the tv_usec field is negative, at least on Linux, so I have to set it
to (a.tv_usec-b.tv_usec)%1000000, and then add 1000000 if the result is
negative.)
Rennie
the C language, both of which are apparently correct. Could someone
please explain the reasoning behind them?
1. The operators '^', '&', and '|' have lower precedance than '==',
'!=', '>=", etc. I discovered this when the statement "if (array1 ^
array2 == 0xff)" failed to do what I expected. To me, it doesn't
make any sense to give the bitwise operators lower precedance than
comparators. I can't see any situation where someone would want to
perform a bitwise operation on a truth value, but that is what the
language specifies for the above expression.
2. In C99, the expression 'a%b' where a<0 and b>0 will return a negative
result (K&R lets this be machine dependent). While it is technically
correct (-1 is congruent to 6 mod 7), it isn't exactly what most people
expect. Mathematically, the congruence classes modulo n are usually
expressed as [0], [1], ... [n-1]. The value -1 would be a member of the
congruence class [n-1]. So, when I'm performing certain operations, I
have to check if a number is negative, and if so, add the modulus to the
residue to get a sensible result. (For example, when subtracting two
struct timevals, and passing the result to select(). select() will barf
if the tv_usec field is negative, at least on Linux, so I have to set it
to (a.tv_usec-b.tv_usec)%1000000, and then add 1000000 if the result is
negative.)
Rennie