Rounding during division

C

Christopher Key

Hello,

Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?


Secondly, is there anything that I can rely when right shifting a
negative int32_t. Given that int32_t is guaranteed to be stored in
two's complement format, can it be assumed that right shifting by N is
the same as division by 2^N with rounding towards -inf? e.g:

printf("%d", 3>>1); // 1
printf("%d", 1>>1); // 0
printf("%d", -1>>1); // -1
printf("%d", -3>>1); // -3

If bitwise operations have undefined behaviour on negative intN_t types,
what was the point in specifying that they must be in two's complement
format?

Regards,

Chris
 
A

Army1987

Hello,

Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?
Yes.
Secondly, is there anything that I can rely when right shifting a
negative int32_t. Given that int32_t is guaranteed to be stored in
two's complement format, can it be assumed that right shifting by N is
the same as division by 2^N with rounding towards -inf? e.g:

printf("%d", 3>>1); // 1
printf("%d", 1>>1); // 0
printf("%d", -1>>1); // -1
printf("%d", -3>>1); // -3

If bitwise operations have undefined behaviour on negative intN_t types,
what was the point in specifying that they must be in two's complement
format?

Bitwise shifts on signed integers are implementation defined. For
example the sign bit may be treated differently.
 
R

Ralf Damaschke

Army1987 said:

No. That is only true for C99.
There are still many C89-C95 implementations and they were
allowed to make their own decision:

| If either operand is negative, whether the
| result of the / operator is the largest integer less than the
| algebraic quotient or the smallest integer greater than the
| algebraic quotient is implementation-defined, as is the sign
| of the result of the % operator.

Ralf
 
M

Mark McIntyre


No. For the positive cases, you can rely on it. For the negative
cases, compilers may round up or down, depending on which version of
the C standard they comply to.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
 
O

Old Wolf


In fact it is implementation-defined in C90, whether it
rounds up or down for negative intergers.
Bitwise shifts on signed integers are implementation defined.

No. There are four cases:
1. Right-shift of non-negative value: well-defined
2. Right-shift of negative value: implementation-defined
3. Left-shift of negative value: undefined
4. Left-shift of non-negative value: undefined if the
shift would cause an overflow, otherwise well-defined
 
C

Christopher Key

Old said:
In fact it is implementation-defined in C90, whether it
rounds up or down for negative intergers.


No. There are four cases:
1. Right-shift of non-negative value: well-defined
2. Right-shift of negative value: implementation-defined
3. Left-shift of negative value: undefined
4. Left-shift of non-negative value: undefined if the
shift would cause an overflow, otherwise well-defined

Thanks,

Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.

2) Check the compiler against a list of known okay compilers. This
seems very messy.

3) Write code that manually implements the required behaviour, e.g.:

x = (x & ~3) / 4

It seems a little hopeful to assume that the compiler would be able to
optimise this into an arithmetic shift though, and it's certainly not as
self documenting.

Any thoughts?

Regards,

Chris
 
J

Justin Spahr-Summers

Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.

typedef int assertion_dummy_array[(-value >> shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.
 
C

Charlie Gordon

Justin Spahr-Summers said:
Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.

typedef int assertion_dummy_array[(-value >> shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.

Of course you can test implementation defined behaviour at run time and at
compile time in this case (call it static_assert).
But you want to do this at the preprocessing stage in order to select the
proper code for the implementation. There is no guarantee that the
preprocessor use the same arithmetics as the target, so you cannot rely on
#if (-1 >> 1) == -1 for instance. One would need explicit macros along the
lines of INT_MAX to detect what type of integer representation is used, what
type of arithmetics, and so on.
 
C

Christopher Key

Justin said:
Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.

typedef int assertion_dummy_array[(-value >> shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.

I'll give that a go. It'd be interesting to know how many compilers
warn correctly in all cases, even when cross compiling for a platform
with different shift instructions available to those on the host.

Regards,

Chris
 
C

Christopher Key

Charlie said:
Justin Spahr-Summers said:
Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.
typedef int assertion_dummy_array[(-value >> shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.

Of course you can test implementation defined behaviour at run time and at
compile time in this case (call it static_assert).
But you want to do this at the preprocessing stage in order to select the
proper code for the implementation. There is no guarantee that the
preprocessor use the same arithmetics as the target, so you cannot rely on
#if (-1 >> 1) == -1 for instance. One would need explicit macros along the
lines of INT_MAX to detect what type of integer representation is used, what
type of arithmetics, and so on.

Presumably, all that INT_MAX and INT_MIN will tell you is whether you're
using a two's complement machine or not, and there's no guarantee that a
specific shift behaviour has been implemented.

I guess that the safest way is to simply perform a runtime check.

Regards,

Chris
 
C

Charlie Gordon

Christopher Key said:
Charlie said:
Justin Spahr-Summers said:
Is there any clean, portable way of acheiving signed integer division
by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with
an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.
typedef int assertion_dummy_array[(-value >> shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.

Of course you can test implementation defined behaviour at run time and
at compile time in this case (call it static_assert).
But you want to do this at the preprocessing stage in order to select the
proper code for the implementation. There is no guarantee that the
preprocessor use the same arithmetics as the target, so you cannot rely
on #if (-1 >> 1) == -1 for instance. One would need explicit macros
along the lines of INT_MAX to detect what type of integer representation
is used, what type of arithmetics, and so on.

Presumably, all that INT_MAX and INT_MIN will tell you is whether you're
using a two's complement machine or not, and there's no guarantee that a
specific shift behaviour has been implemented.

I guess that the safest way is to simply perform a runtime check.

Except c99 6.5.7 specifies that sight shifting a signed type with negative
value results in an implementation defined result but does not give an
exhaustive list of possible implementations. To correctly detect at runtime
a given 'expected' behaviour (such as ARS or LSR) one would need to conduct
an exhaustive test of all possible shift operands. Furthermore,
implementation defined behaviour includes terminating the program (a known
characteristic of the DS9K)

Definitely, a few macros in stdint specifying INT_RIGHT_SHIFT_IS_SIGNED or
similar could help. The same goes for macros telling about integer
representation and other signed arithmetic specifics.
 
C

CBFalconer

Charlie said:
.... snip ...

Except c99 6.5.7 specifies that sight shifting a signed type with
negative value results in an implementation defined result but
does not give an exhaustive list of possible implementations. To
correctly detect at runtime a given 'expected' behaviour (such as
ARS or LSR) one would need to conduct an exhaustive test of all
possible shift operands. Furthermore, implementation defined
behaviour includes terminating the program (a known characteristic
of the DS9K)

Check your supplier. Your DS9K lacks the latest improvements. Mine,
in the same circumstances, submits a fake tax return to the IRS,
with flags that ensure the IRS pulls it for examination. The fake
return has material that proves you hid 10,000,000 USD (or more)
income last year, and makes you liable for the tax, penalties,
etc.

After this action the machine terminates, after wiping out all
traces of actions taken since the (attempted) right shift of a
negative value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top