Too circuitous for a Macro?
June 5th, 2008
Let’s imagine you need a make some letter’s uppercase. I would usually use the build in CString function or too make it very simple something like this:
string toupper(const string& str) { string s = str; int len = s.length(); for(int i = 0; i < len; i++) if( s[i] >= 'a' && s[i] <= 'z' ) s[i] -= 32; return s; }
or if I wanted to stuck more to C-style:
for ( int a = 0; a < strlen ( mystring ); a++ ) if ( mystring [ a ] >= 'a' && mystring [ a ] <= 'z' ) mystring [ a ] &= 0xdf;
Some people prefer using macros for short operations.
The advantage of a macro is that it can be type-neutral (this can also be a disadvantage, of course), and it’s inlined directly into the code, so there isn’t any function call overhead. (Note that in C++, it’s possible to get around both of these issues with templated functions and the inline keyword.)
In C++, you should generally avoid macros when possible. You won’t be able to avoid them entirely if you need the ability to paste tokens together, but with templated classes and type inference for templated functions, you shouldn’t need to use macros to create type-neutral code.
Another reason the prevent usage is that debugging a macro is not that comfortable…
Nevertheless a correct macro would be:
#define TO_UPPER(c) ( ((c)>='a'&&(c)<='z') ? ((c)-'a'+'A') : (c) )
It’s short, readable and particularly reuseable.
Now we come to the piece of code I really wanted to get at. I found it yesterday night in a project I don’t want to embarrass in public (No, I DIDN’T find it at work!):
// Macro to normalize table names // (all of them will be stored in upper case ) #define TO_UPPER( x )( \ ( 'a' == ( x ) ) ? 'A' : \ ( 'b' == ( x ) ) ? 'B' : \ ( 'c' == ( x ) ) ? 'C' : \ ( 'd' == ( x ) ) ? 'D' : \ ( 'e' == ( x ) ) ? 'E' : \ ( 'f' == ( x ) ) ? 'F' : \ ( 'g' == ( x ) ) ? 'G' : \ ( 'h' == ( x ) ) ? 'H' : \ ( 'i' == ( x ) ) ? 'I' : \ ( 'j' == ( x ) ) ? 'J' : \ ( 'k' == ( x ) ) ? 'K' : \ ( 'l' == ( x ) ) ? 'L' : \ ( 'm' == ( x ) ) ? 'M' : \ ( 'n' == ( x ) ) ? 'N' : \ ( 'o' == ( x ) ) ? 'O' : \ ( 'p' == ( x ) ) ? 'P' : \ ( 'q' == ( x ) ) ? 'Q' : \ ( 'r' == ( x ) ) ? 'R' : \ ( 's' == ( x ) ) ? 'S' : \ ( 't' == ( x ) ) ? 'T' : \ ( 'u' == ( x ) ) ? 'U' : \ ( 'v' == ( x ) ) ? 'V' : \ ( 'w' == ( x ) ) ? 'W' : \ ( 'x' == ( x ) ) ? 'X' : \ ( 'y' == ( x ) ) ? 'Y' : \ ( 'z' == ( x ) ) ? 'Z' : ( x ) \ )
I really didn’t want to deprive this of you.
Pretty cool to write this really terrifying macro instead of:
#define TO_UPPER(c) c^0x20
which is indeed the shortest way ![]()






Dedicated servers now available - Cheap servers
Comment by Typebealpibralo — November 29, 2011 @ 7:58 pm