tags:

views:

393

answers:

2

I've seen this done in C before:

#define MY_STRING "12345"
...
#define SOMETHING (MY_STRING + 2)

What does SOMETHING get expanded to, here? Is this even legal? Or do they mean this?:

#define SOMETHING (MY_STRING[2])
+13  A: 

When you have an array or pointer, p+x is equivalent to &p[x]. So MY_STRING + 2 is equivalent to &MY_STRING[2]: it yields the address of the third character in the string.

Notice what happens when you add 0. MY_STRING + 0 is the same as &MY_STRING[0], both of which are the same as writing simply MY_STRING since a string reference is nothing more than a pointer to the first character in the string. Happily, then, the identity operation "add 0" is a no-op. Consider this a sort of mental unit test we can use to check that our idea about what + means is correct.

John Kugelman
I think my hangup here was that I didn't know that a quoted string was equal to the character array, at least syntax-wise. Thanks. +1.
Joe
+33  A: 

String literals exist in the fixed data segment of the program, so they appear to the compiler as a type of pointer.

+-+-+-+-+-+--+
|1|2|3|4|5|\0|
+-+-+-+-+-+--+
 ^ MY_STRING
     ^ MY_STRING + 2
Ignacio Vazquez-Abrams
+1 for ASCII art.
Skurmedel
Can one do this (using + sign) with Unicode as well?
Hamish Grubijan
I too love ASCII art, so I have to vote this one as the answer.
Joe
so this one win for the ASCII art... ;)
Reigel
@Hamish Grubijan: Yes, the same will go for Unicode. The L"StringLiteral" will have `const wchar_t*` type, so `+` will advance by the number of `wchar_t` s.
sharptooth
Throw some votes on the other answer as well, because it's a good complement.
Skurmedel
Men are visual creatures; if it looks good, then it must be right.
Hamish Grubijan