views:

111

answers:

3

Hi,

EDIT: My example might have created some confusion. I have changed the example below to reflect what I want to achieve. Hope this is more clear.

I am trying to define a constant in my objective-c code. I am using the standard #define to do this. Eg:

#define bluh "a"

I would like to define another constant like this

#define blah bluh +@"b"

The compiler throws up an error (rightly so) "invalid operands to binary +". How can I get this to work? Thanks for the help.

I also tried the Objective-C way like this:

NSString *const A =@"a";
NSString *const B = [NSString stringWithFormat:@"%@%@",A,@"b"];

But this gives me another error "Initializer element is not constant" Any help will be appreciated.

Cheers,

A: 

http://stackoverflow.com/questions/538996/constants-in-objective-c

ennuikiller
That's not the same, iSee wants to create a new macro based off the expansion of another macro.
dreamlax
+2  A: 

I don't know objective C. In C++, adjacent string literals are concatenated, so it's adequate to use:

#define blah bluh "b"

BTW / it's standard practice to use uppercase for preprocessor defines wherever possible, and for no other purpose, minimising the chance of unexpected substitutions.

Tony
I don't mind if it is c++, but this solution works. Thanks Tony.
iSee
@Stephen: actually, no. If you put "a" "b" anywhere in a C++ program - quite independent of any preprocessor use - the C++ compiler will concatenate the literals. For example, cout << "first line\n" "second line\n";. Consequently, you don't need a <<, or a separate statement again mentioning the stream, between lines that begin and end with string literal streaming, and it's (usually trivially) inefficient to put them there. Separately, why qualify the preprocessor as the "C" preprocessor - may happen to be the same, but then so are lots of C++ features. Is "int x" of type "C int"?
Tony
+1  A: 

In standard c/c++ you can concatenate literal strings by just placing them next to each other e.g. "string one-" "string two" will become "string one-string two" after the compiler has its way with it.

Not sure if this will work with the '@' symbol you've got at the start, but just try doing:

#define bluh "a"
#define blah bluh @"b"

Haven't had that much experience with Objective-C, but hopefully they kept this part inter operable.

Grant Peters
All valid C code is valid Objective-C code, and the behavior is the same. The language Objective-C is an incredibly minimal extension to C. That said, questioner wants to do exactly what you suggest, but without the `@` symbol.
Stephen Canon