Hi,
On 10/25/10, Adriaan van Os gpc@microbizz.nl wrote:
But Adriaan explicitly asked about standard Pascal
You are right. But I wonder how many Pascal programmers are wrong here.... It is very tricky. What about a compiler warning ?
C:\BLAH [ GPC ] >gpc --classic-pascal -s -O adrian.pas -o adrian.exe -Wall -Wextra adrian.pas: In main program: adrian.pas:3: error: syntax error before `shr'
Consider that your warning. ISO doesn't support "shr". ;-) In all seriousness, I would doubt the FPC answer would ever be considered correct in this context (heh, 9 gazillion from "-2 shr 1"? highly unlikely). I'm sure they'll be glad for a test case / bug report.
{ gp -s -O unary } { GPC 20070904, GCC 3.4.4 + DJGPP } { d:\fpc242\bin\go32v2\fpc -XXs -Os -al unary } program unary; begin writeln( -1 ); {-1} writeln( 2 shr 1 ); { 1} writeln((-2)shr 1 ); {GPC: -1 FPC: 9223372036854775807} writeln(-(2 shr 1)); {-1} writeln( -2 shr 1 ); {GPC: -1 FPC: 9223372036854775807} writeln( -2 div 2 ); {-1} end.
I know this was meant to be a trivial case, and I'm probably stating the extremely obvious, but ... just use Pascal's "div", that's what it's for. Using BP's "shr" here (presumably same as x86's "sar" instruction, which is what ANSI C ">>" uses, right??) is probably a misguided case of premature optimization. Granted, as long as it works for you ... but it's clearly not totally extremely obvious nor totally portable. However, I'm no mathematician and hadn't truly stumbled upon nor understood this previously myself.