Monday, July 20, 2015

Charizing Operator (#@) Does Not Work On MAC OSX

 #include <iostream>  
 using std::cout;  
 using std::endl;  
 #define Charizing(x) #@x  
 int main()  
 {  
   cout << Charizing(a) << endl;  
   cout << Charizing(b1) << endl;  
 }  
First, let's study above program. The output is
a
25137

Basically, Charizing(x) encloses the parameter x with single quotation mark and treats it as a character. That's why Charizing(a) returns a. However, when x is not a character, the output is some strange number. I guess the number is converted from type of parameter to char.

However, the above program is not compilable in Xcode. The error is '#' is not followed by a macro parameter.

As far as I know, Stringizing operator (#) and Token-pasting operator (##) work fine on Xcode, except Token-pasting operator (##). According to MSDN, Token-pasting operator (##) is a Microsoft specific. This is why it is not supported in Xcode.

To fix the program to work on both Windows and MAC OSX, we can first convert the parameter x to string and then get the first character. We suppose that x always contains one character with "#x[0]".
 #include <iostream>  
 using std::cout;  
 using std::endl;  
 #define Charizing(x) #x[0]  
 int main()  
 {  
   cout << Charizing(a) << endl;  
   cout << Charizing(b1) << endl;  
 }  
Thus,  we can remember #@x is equal to #x[0], assume that x is a one-char string.


No comments:

Post a Comment