7

Despite the fact that this is not good coding practice, I want a macro that should work like the following:

CREATE_STRING(fooBar)

And it should create the following code:

NSString *fooBar = @"fooBar";

My macro looks like this:

#define CREATE_STRING(varName) NSString *varName = @"varName";

But now I get the following

NSString *fooBar = @"varName";

It seems to be such an easy problem to solve and I have already checked the documentation from IBM but I just can't seem to get the varName into the string.

2 Answers 2

15

Use

#define CREATE_STRING(varName) NSString *varName = @#varName

instead. (also note that you don't need the trailing semicolon in order to be able to "call" your macro as a C-like function.)

Sign up to request clarification or add additional context in comments.

13 Comments

[...]Untitled.m:7:34: error: use of undeclared identifier 'foo'; did you mean 'for'? NSString *mary = CREATE_STRING(foo); ^ Untitled.m:3:42: note: expanded from macro 'CREATE_STRING' #define CREATE_STRING(varName) NSString *varName = @#varName ^ 2 errors generated.
Did you call it as CREATE_STRING(foo); (with a semicolon at the end when calling)? If not, try to do so. The error is NOT at the point the macro is used.
I just swapped your macro definition for mine to get that error, yours can't work. You can only stringify macros in the preprocessor, so the approach I used in my answer is needed to convert the bare characters into a macro before it gets stringified.
"You can only stringify macros in the preprocessor" <- nope. Arguments can be stringified as well.
+1 I just have tested this answer and it is perfectly fine. Until I tried it I thought @#varName would be a syntax error.
|
10

This is how to do it

#define CREATE_STRING(varName) NSString *varName = @"" #varName

It takes advantage of the fact that two string constants one after the other get concatenated by the compiler.

10 Comments

Did ANYBODY actually try my solution before downvoting?
How is this different to @H2CO3's answer?
It's different in that it concatenates two strings, not just inserts the C-stringified name after the '@'.
@H2CO3 He could have commented on your answer and you could have corrected it, couldn't you?
@trojanfoe @H2CO3 When I posted my answer, I adidn't believe the straight @#varName would work, because in olden days it didn't. However, I have just tried it with the current clang compiler and now it does. It was not me, by the way, that downvoted H2CO3's answer. I always post comments when I down vote.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.