Re: pls expand this macro
- From: Simon Biber <news@xxxxxxxxx>
- Date: Mon, 31 Oct 2005 01:07:28 +1100
sathyashrayan wrote:
/* ** PLURALTX.C - How to print proper plurals ** public domain - original algorithm by Bob Stout */
#include <stdio.h>
#define plural_text(n) &"s"[(1 == (n))]
This is equivalent to ( "s" + (1 == (n) ) )
ie. adding 0 or 1 to the starting address of the string literal "s". If adding zero, the result is a pointer to the string "s". If adding one, the result is a pointer to the string "".
#define plural_text2(n) &"es"[(1 == (n))<<1]
This is equivalent to ( "es" + (1 == (n)) * 2 )
ie. adding 0 or 2 to the starting address of the string literal "es". If adding zero, the result is a pointer to the string "es". If adding two, the result is a pointer to the string "".
> i, plural_text2(i));int main(void) { int i;
for (i = 0; i < 10; ++i) printf("%d thing%s in %d box%s\n", i, plural_text(i),
return 0; }
My questions:
1) I try to understand the two macros plural_text and plural_text2. array subscripting is commutative
That's irrelevant. This code uses array subscripting in the usual way, with the array on the left, and the subscript between the brackets.
so in the above we could expand the macros as plural_text n[1] = "s" .
No. Not at all. The invocation plural_text(i) expands to the following eleven tokens: & "s" [ ( 1 == ( i ) ) ]
The parenthesis around the variable (n) since the macros does not know the type of the variable it is acting on. Am I correct?
No. It acts on an expression, not a variable. The parenthesis are in case the expression given contains other operators that may affect the parsing.
2) I don't able to understand the use of & in both of the macros. Does it used for the rule "array decays into the pointer to it's first element"?
The & operator is not applied to the array. It is applied to the expression containing the subscript. That is, it is parsed as
& ( "s"[(1 == (i))] )
rather than
(& "s") [(1 == (i))]
Here's one way to understand it: "s" is an array of two char. That array is subscripted, to give an lvalue referring to either the first or second element of the array, and then the address-of operator is applied to the lvalue, giving a pointer to the first or second element of the array.
3) << operator in the macro plural_text2 used to move the string to the second one, in the above case it is "s". Correct?
The << operator is a binary shift on an integer value. Shifting left by one bit is equivalent to multiplying by two. It has the effect of changing a value that could be 0 or 1, into a value that could be 0 or 2 respectively.
-- Simon. .
- References:
- pls expand this macro
- From: sathyashrayan
- pls expand this macro
- Prev by Date: Re: pls expand this macro
- Next by Date: Re: Order of evaluting functions ?
- Previous by thread: Re: pls expand this macro
- Next by thread: Re: pls expand this macro
- Index(es):
Relevant Pages
|