Pay close attention to that "appropriate type" part, and
view "like int" with caution. The problem is that the result
of right-shifting a negative number is implementation-defined,
and is usually not the same as the result of dividing by two.
For example, on the two's complement machines that are all
but universal nowadays the representation of -1 is a string
of 1-bits. Shift the string one place to the right and you
may get another string of 1-bits ("arithmetic shift") or a
single 0-bit followed by 1-bits ("logical shift"). The first
thus gives -1 again, while the second gives a large positive
result -- but neither gives the correct result -1 / 2 == 0.
So: "appropriate type" means either an *unsigned* integer
or a signed integer that you happen to know is non-negative.
Agreed.
There can be even more problems with negative numbers.
IMHO the definition of the division in C89 allows also
-1 / 2 == -1. Although I did not find a C compiler which
does this, it is theoretically possible since in C89 the
division is defined as follows:
The binary / operator yields the quotient, and the % operator
the remainder, of the first operand by the second; if the
second operand is 0, the result is undefined. Otherwise, it
is always true that (a/b)*b + a%b is equal to a. If both
operands are non-negative, the remainder is non-negative and
smaller than the divisor; if not it is guaranteed only that
the absolute value of the remainder is smaller than the
absolute value of the divisor.
As said before this definition allows that the integer
division can be rounded towards minus infinite.
Note that when -1 / 2 == -1 at the same time -1 % 2 == 1
IMHO this definition was chosen to allow integer operations
with one machine instruction.
Greetings Thomas Mertes
Seed7 Homepage:
http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.