modulus fn with negatives

Guido van Rossum guido at mcvax.UUCP
Tue Sep 11 07:25:56 AEST 1984


How about this modulus function:

	mod(a, b) {
		int m = a % b;
		if ((m < 0) != (b < 0)) m += b;
		return m;
	}

This one even works for negative b.
You can also do the following:

	#define mod(a, b) (a%b + b) % b

which should, of course, be written as

	#define mod(a, b) (((a)%(b) + (b)) % (b))

and this also works for negative b (but watch side effects!).

--
	Guido van Rossum, "Stamp Out BASIC" Committee, CWI, Amsterdam
	guido @ mcvax



More information about the Comp.lang.c mailing list