Re: MATH_MOD: Include in GLib?
- From: Dave Benson <daveb evolution com>
- To: Owen Taylor <otaylor redhat com>
- Cc: drlion-dated-1091219837 02c327 teepee ath cx, Jan Kratochvil <lace jankratochvil net>, gtk-devel-list gnome org, Sven Neumann <sven gimp org>
- Subject: Re: MATH_MOD: Include in GLib?
- Date: Mon, 26 Jul 2004 08:23:54 -0700
On Mon, Jul 26, 2004 at 11:17:48AM -0400, Owen Taylor wrote:
> On Mon, 2004-07-26 at 06:41, Sven Neumann wrote:
> > Hi,
> > Jan Kratochvil <lace jankratochvil net> writes:
> > > On Mon, 26 Jul 2004 10:43:21 +0200, Sven Neumann wrote:
> > > > Daniel Brockman <drlion deepwood net> writes:
> > > ...
> > > > > #define MOD(x, m) ((x) >= 0 ? (x) % (m) : (m) + (x) % (m))
> > > ...
> > > > If at all it would have to be G_MOD(x). But I doubt that
> > > > the semantics of such a macro are obvious enough and that it would be
> > > > of general usefulness.
> > >
> > > I consider this macro as a generally used workaround of a bug in C standard.
> > > I intuitively expect the result of "x%m" will be 0..(m-1), not the C result
> > > of -(m-1)..(m-1). It has similiar position as G_N_ELEMENTS().
> > The result of "x%m" will be 0..(m-1) provided that you respect the
> > fact that the modulo operator is undefined on negative operands. The
> > behaviour is machine-dependent and you should simply avoid to use
> > modulo with signed variables.
> Are you sure about this? In my understanding, the C standard defines
> division as truncation towards zero. And then defines:
> a % b == a - b * (a / b)
it's a c99-ism. quoting http://home.tiscalinet.ch/t_wolf/tw/c/c9x_changes.html
The integer division and modulus operators are defined to perform truncation towards zero. (In C89, it was implementation-defined whether truncation was done towards zero or -infinity. This is (obviously) important only if one or both operands are negative. Consider:
-22 / 7 = -3
-22 % 7 = -1
truncation towards zero
-22 / 7 = -4
-22 % 7 = 6
truncation towards -infinity
Both satisfy the required equation (a/b)*b + a%b == a. The second has the advantage that the modulus is always positive -- but they decided on the other (more Fortran-like, less Pascal-like) variant...)
] [Thread Prev