[comp.lang.c] macro inefficiency

utility@quiche.cs.mcgill.ca (Ronald BODKIN) (09/27/90)

In article <2514@cirrusl.UUCP> dhesi%cirrusl@oliveb.ATC.olivetti.com (Rahul Dhesi) writes:
[suggesting a swap macro with typeof:]
>I have seen a "typeof" keyword proposed that would fix this deficieny:
>
>#define swap(a,b)  do { typeof(a) tmp; tmp = a;  a = b; b = tmp; } until (0);
	This should just be defined as:
#define swap(a,b)  { typeof(a) tmp; tmp = a;  a = b; b = tmp; }

(check out your C grammar carefully and you will see that
{ declaration* statement* } is always a valid statement).

		Ron

pmk@craycos.com (Peter Klausler) (10/01/90)

In article <5062@quiche.cs.mcgill.ca> utility@quiche.cs.mcgill.ca (Ronald BODKIN) writes:
>In article <2514@cirrusl.UUCP> dhesi%cirrusl@oliveb.ATC.olivetti.com (Rahul Dhesi) writes:
>[suggesting a swap macro with typeof:]
>>I have seen a "typeof" keyword proposed that would fix this deficieny:
>>
>>#define swap(a,b)  do { typeof(a) tmp; tmp = a;  a = b; b = tmp; } until (0);
>	This should just be defined as:
>#define swap(a,b)  { typeof(a) tmp; tmp = a;  a = b; b = tmp; }
>
>(check out your C grammar carefully and you will see that
>{ declaration* statement* } is always a valid statement).

Check out your C grammar even more carefully and you will see that

	#define swap (a,b) { typeof (a) tmp; tmp = a; a = b; b = tmp; }

		if (...)
			swap (a,b);
		else
			...

is erroneous, while

	#define swap (a,b) do { typeof (a) tmp; tmp = a; a = b; b = tmp; } \
				while (0)

		if (...)
			swap (a,b);
		else
			...

works.

(Note that it's "do {...} while (...)", not "do {...} until (...);".)

-Peter Klausler, Cray Computer Corp. compiler development

utility@quiche.cs.mcgill.ca (Ronald BODKIN) (10/02/90)

In article <1990Oct1.002217.4945@craycos.com> pmk@craycos.com (Peter Klausler) writes:
[that
	#define swap (a,b) { typeof (a) tmp; tmp = a; a = b; b = tmp; }
fails for if (..) swap(a,b); else ..., while changing the original to
>	#define swap (a,b) do { typeof (a) tmp; tmp = a; a = b; b = tmp; } \
>				while (0)
	works].
		Quite right (also pointed out to me in email), although
mine was better than the original, and if one's compiler doesn't optimize
away conditionals with fixed values, it produces better code.  However,
the idea of using do { ... } while (0) to allow a statement that is
closed by a semicolon is a good one.
		Ron

dhesi%cirrusl@oliveb.ATC.olivetti.com (Rahul Dhesi) (10/04/90)

>(Note that it's "do {...} while (...)", not "do {...} until (...);".)

Going back to the old discussion of "How do you define a wizard?",
here's one more:

A real wizard knows the difference between somebody else not knowing
something, and somebody else knowing something but slipping up.  In the
first case, the real wizard gently corrects the errant person.  In the
second, he quietly lets it pass.
--
Rahul Dhesi <dhesi%cirrusl@oliveb.ATC.olivetti.com>
UUCP:  oliveb!cirrusl!dhesi