Re: tolower macro
- From: Thomas Richter <thor@xxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: 09 Aug 2006 16:50:11 GMT
doskix@xxxxxxxxx wrote:
I was looking at <CTYPES.H> after chatting with some friends about
binary math. What I saw, and researched a little is that historically,
tolower is a macro defined like this.
#define _tolower(_c) ((_c)-'A'+'a')
Which is, though, incorrect. Who says the input is ASCII? Who says the
input is upper case?
And, what I'm thinking about is that a decrement and then an increment
takes more instructions than a bit flip.
Almost any C compiler I'm aware off would optimize this to a single
addition instruction.
Decimal 32 is the diference
between a lower case character and it's uppercase equivalent. So, the
lowercase value of a number is as easy to get as flipping bit 6, which
can be implement by an or of 32 decimal...which is an ascii space.
#define _mytolower(_c) ((_c)|' ')
Which would still not work correctly for, say, '0'. It's not faster
than the above either on typical hardware. The above solution uses
one add, this one uses one "or". No big deal.
Typically, tolower() goes into a lookup table or some more sophisticated
algorithm.
I'm curious, because I hear that a regular preprocessor is like a
search and replace:
Approximately.
But I don't know about these function like macros.
Quite the same, except that the argument is renamed.
mytolower(arg)
is replaced by
(arg | ' ')
and
mytolower('A')
by
('A' | ' ')
My question is how do they get expanded. Does the preprocessor just
insert the "return" value,
No. It replaces the placeholder argument of the macro definition
by the argument given at the invocation of the macro.
If that's the case, I think they'd still have to be
optimized...
They *could* be optimized if the compiler chooses to do so. But
that's nothing a macro can know or care about.
What do you guys think? How do macros like these get expanded and would
this macro be faster than the tradition tolower?
It would be, for first, incorrect. First write correct programs, then
check whether the speed is sufficient, and if not, identify the
bottleneck. Then try to find faster solutions. Do not try to replace
correct by incorrect code for the sake of speed.
Besides, on typical hardware I'm aware of, the two solutions would
be executed at exactly the same speed given even a remotely modern
compiler.
HTHH,
Thomas
--
comp.lang.c.moderated - moderation address: clcm@xxxxxxxxxxxx -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
.
- References:
- tolower macro
- From: doskix
- tolower macro
- Prev by Date: Re: about static int 2D array
- Next by Date: Re: tolower macro
- Previous by thread: Re: tolower macro
- Next by thread: Re: tolower macro
- Index(es):
Relevant Pages
|