3

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,

iSee
  • 604
  • 14
  • 31

2 Answers2

2

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 Delroy
  • 99,066
  • 13
  • 167
  • 246
  • I don't mind if it is c++, but this solution works. Thanks Tony. – iSee Aug 26 '10 at 02:23
  • 1
    @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 < – Tony Delroy Aug 26 '10 at 03:05
1

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
  • 7,461
  • 3
  • 42
  • 57
  • 1
    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 Aug 26 '10 at 02:29
  • 1
    And in Objective-C, it also works if you use the @ prefix. @"1" "2" "3" is the same as @"123". – gnasher729 Sep 16 '14 at 16:10